id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
9,900
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/event_builder/index.js
|
function(options) {
var impressionEvent = {
httpVerb: HTTP_VERB
};
var commonParams = getCommonEventParams(options);
impressionEvent.url = ENDPOINT;
var impressionEventParams = getImpressionEventParams(options.configObj, options.experimentId, options.variationId);
// combine Event params into visitor obj
commonParams.visitors[0].snapshots.push(impressionEventParams);
impressionEvent.params = commonParams;
return impressionEvent;
}
|
javascript
|
function(options) {
var impressionEvent = {
httpVerb: HTTP_VERB
};
var commonParams = getCommonEventParams(options);
impressionEvent.url = ENDPOINT;
var impressionEventParams = getImpressionEventParams(options.configObj, options.experimentId, options.variationId);
// combine Event params into visitor obj
commonParams.visitors[0].snapshots.push(impressionEventParams);
impressionEvent.params = commonParams;
return impressionEvent;
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"impressionEvent",
"=",
"{",
"httpVerb",
":",
"HTTP_VERB",
"}",
";",
"var",
"commonParams",
"=",
"getCommonEventParams",
"(",
"options",
")",
";",
"impressionEvent",
".",
"url",
"=",
"ENDPOINT",
";",
"var",
"impressionEventParams",
"=",
"getImpressionEventParams",
"(",
"options",
".",
"configObj",
",",
"options",
".",
"experimentId",
",",
"options",
".",
"variationId",
")",
";",
"// combine Event params into visitor obj",
"commonParams",
".",
"visitors",
"[",
"0",
"]",
".",
"snapshots",
".",
"push",
"(",
"impressionEventParams",
")",
";",
"impressionEvent",
".",
"params",
"=",
"commonParams",
";",
"return",
"impressionEvent",
";",
"}"
] |
Create impression event params to be sent to the logging endpoint
@param {Object} options Object containing values needed to build impression event
@param {Object} options.attributes Object representing user attributes and values which need to be recorded
@param {string} options.clientEngine The client we are using: node or javascript
@param {string} options.clientVersion The version of the client
@param {Object} options.configObj Object representing project configuration, including datafile information and mappings for quick lookup
@param {string} options.experimentId Experiment for which impression needs to be recorded
@param {string} options.userId ID for user
@param {string} options.variationId ID for variation which would be presented to user
@return {Object} Params to be used in impression event logging endpoint call
|
[
"Create",
"impression",
"event",
"params",
"to",
"be",
"sent",
"to",
"the",
"logging",
"endpoint"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/event_builder/index.js#L165-L180
|
|
9,901
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/event_builder/index.js
|
function(options) {
var conversionEvent = {
httpVerb: HTTP_VERB,
};
var commonParams = getCommonEventParams(options);
conversionEvent.url = ENDPOINT;
var snapshot = getVisitorSnapshot(options.configObj,
options.eventKey,
options.eventTags,
options.logger);
commonParams.visitors[0].snapshots = [snapshot];
conversionEvent.params = commonParams;
return conversionEvent;
}
|
javascript
|
function(options) {
var conversionEvent = {
httpVerb: HTTP_VERB,
};
var commonParams = getCommonEventParams(options);
conversionEvent.url = ENDPOINT;
var snapshot = getVisitorSnapshot(options.configObj,
options.eventKey,
options.eventTags,
options.logger);
commonParams.visitors[0].snapshots = [snapshot];
conversionEvent.params = commonParams;
return conversionEvent;
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"conversionEvent",
"=",
"{",
"httpVerb",
":",
"HTTP_VERB",
",",
"}",
";",
"var",
"commonParams",
"=",
"getCommonEventParams",
"(",
"options",
")",
";",
"conversionEvent",
".",
"url",
"=",
"ENDPOINT",
";",
"var",
"snapshot",
"=",
"getVisitorSnapshot",
"(",
"options",
".",
"configObj",
",",
"options",
".",
"eventKey",
",",
"options",
".",
"eventTags",
",",
"options",
".",
"logger",
")",
";",
"commonParams",
".",
"visitors",
"[",
"0",
"]",
".",
"snapshots",
"=",
"[",
"snapshot",
"]",
";",
"conversionEvent",
".",
"params",
"=",
"commonParams",
";",
"return",
"conversionEvent",
";",
"}"
] |
Create conversion event params to be sent to the logging endpoint
@param {Object} options Object containing values needed to build conversion event
@param {Object} options.attributes Object representing user attributes and values which need to be recorded
@param {string} options.clientEngine The client we are using: node or javascript
@param {string} options.clientVersion The version of the client
@param {Object} options.configObj Object representing project configuration, including datafile information and mappings for quick lookup
@param {string} options.eventKey Event key representing the event which needs to be recorded
@param {Object} options.eventTags Object with event-specific tags
@param {Object} options.logger Logger object
@param {string} options.userId ID for user
@return {Object} Params to be used in conversion event logging endpoint call
|
[
"Create",
"conversion",
"event",
"params",
"to",
"be",
"sent",
"to",
"the",
"logging",
"endpoint"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/event_builder/index.js#L195-L212
|
|
9,902
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js
|
evaluate
|
function evaluate(condition, userAttributes, logger) {
if (condition.type !== CUSTOM_ATTRIBUTE_CONDITION_TYPE) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNKNOWN_CONDITION_TYPE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
var conditionMatch = condition.match;
if (typeof conditionMatch !== 'undefined' && MATCH_TYPES.indexOf(conditionMatch) === -1) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNKNOWN_MATCH_TYPE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
var attributeKey = condition.name;
if (!userAttributes.hasOwnProperty(attributeKey) && conditionMatch != EXISTS_MATCH_TYPE) {
logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.MISSING_ATTRIBUTE_VALUE, MODULE_NAME, JSON.stringify(condition), attributeKey));
return null;
}
var evaluatorForMatch = EVALUATORS_BY_MATCH_TYPE[conditionMatch] || exactEvaluator;
return evaluatorForMatch(condition, userAttributes, logger);
}
|
javascript
|
function evaluate(condition, userAttributes, logger) {
if (condition.type !== CUSTOM_ATTRIBUTE_CONDITION_TYPE) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNKNOWN_CONDITION_TYPE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
var conditionMatch = condition.match;
if (typeof conditionMatch !== 'undefined' && MATCH_TYPES.indexOf(conditionMatch) === -1) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNKNOWN_MATCH_TYPE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
var attributeKey = condition.name;
if (!userAttributes.hasOwnProperty(attributeKey) && conditionMatch != EXISTS_MATCH_TYPE) {
logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.MISSING_ATTRIBUTE_VALUE, MODULE_NAME, JSON.stringify(condition), attributeKey));
return null;
}
var evaluatorForMatch = EVALUATORS_BY_MATCH_TYPE[conditionMatch] || exactEvaluator;
return evaluatorForMatch(condition, userAttributes, logger);
}
|
[
"function",
"evaluate",
"(",
"condition",
",",
"userAttributes",
",",
"logger",
")",
"{",
"if",
"(",
"condition",
".",
"type",
"!==",
"CUSTOM_ATTRIBUTE_CONDITION_TYPE",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNKNOWN_CONDITION_TYPE",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
")",
")",
";",
"return",
"null",
";",
"}",
"var",
"conditionMatch",
"=",
"condition",
".",
"match",
";",
"if",
"(",
"typeof",
"conditionMatch",
"!==",
"'undefined'",
"&&",
"MATCH_TYPES",
".",
"indexOf",
"(",
"conditionMatch",
")",
"===",
"-",
"1",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNKNOWN_MATCH_TYPE",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
")",
")",
";",
"return",
"null",
";",
"}",
"var",
"attributeKey",
"=",
"condition",
".",
"name",
";",
"if",
"(",
"!",
"userAttributes",
".",
"hasOwnProperty",
"(",
"attributeKey",
")",
"&&",
"conditionMatch",
"!=",
"EXISTS_MATCH_TYPE",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"DEBUG",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"MISSING_ATTRIBUTE_VALUE",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
",",
"attributeKey",
")",
")",
";",
"return",
"null",
";",
"}",
"var",
"evaluatorForMatch",
"=",
"EVALUATORS_BY_MATCH_TYPE",
"[",
"conditionMatch",
"]",
"||",
"exactEvaluator",
";",
"return",
"evaluatorForMatch",
"(",
"condition",
",",
"userAttributes",
",",
"logger",
")",
";",
"}"
] |
Given a custom attribute audience condition and user attributes, evaluate the
condition against the attributes.
@param {Object} condition
@param {Object} userAttributes
@param {Object} logger
@return {?Boolean} true/false if the given user attributes match/don't match the given condition,
null if the given user attributes and condition can't be evaluated
|
[
"Given",
"a",
"custom",
"attribute",
"audience",
"condition",
"and",
"user",
"attributes",
"evaluate",
"the",
"condition",
"against",
"the",
"attributes",
"."
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js#L57-L77
|
9,903
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js
|
existsEvaluator
|
function existsEvaluator(condition, userAttributes) {
var userValue = userAttributes[condition.name];
return typeof userValue !== 'undefined' && userValue !== null;
}
|
javascript
|
function existsEvaluator(condition, userAttributes) {
var userValue = userAttributes[condition.name];
return typeof userValue !== 'undefined' && userValue !== null;
}
|
[
"function",
"existsEvaluator",
"(",
"condition",
",",
"userAttributes",
")",
"{",
"var",
"userValue",
"=",
"userAttributes",
"[",
"condition",
".",
"name",
"]",
";",
"return",
"typeof",
"userValue",
"!==",
"'undefined'",
"&&",
"userValue",
"!==",
"null",
";",
"}"
] |
Evaluate the given exists match condition for the given user attributes
@param {Object} condition
@param {Object} userAttributes
@returns {Boolean} true if both:
1) the user attributes have a value for the given condition, and
2) the user attribute value is neither null nor undefined
Returns false otherwise
|
[
"Evaluate",
"the",
"given",
"exists",
"match",
"condition",
"for",
"the",
"given",
"user",
"attributes"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js#L140-L143
|
9,904
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js
|
greaterThanEvaluator
|
function greaterThanEvaluator(condition, userAttributes, logger) {
var conditionName = condition.name;
var userValue = userAttributes[conditionName];
var userValueType = typeof userValue;
var conditionValue = condition.value;
if (!fns.isFinite(conditionValue)) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_CONDITION_VALUE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
if (userValue === null) {
logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE_NULL, MODULE_NAME, JSON.stringify(condition), conditionName));
return null;
}
if (!fns.isNumber(userValue)) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE, MODULE_NAME, JSON.stringify(condition), userValueType, conditionName));
return null;
}
if (!fns.isFinite(userValue)) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.OUT_OF_BOUNDS, MODULE_NAME, JSON.stringify(condition), conditionName));
return null;
}
return userValue > conditionValue;
}
|
javascript
|
function greaterThanEvaluator(condition, userAttributes, logger) {
var conditionName = condition.name;
var userValue = userAttributes[conditionName];
var userValueType = typeof userValue;
var conditionValue = condition.value;
if (!fns.isFinite(conditionValue)) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_CONDITION_VALUE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
if (userValue === null) {
logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE_NULL, MODULE_NAME, JSON.stringify(condition), conditionName));
return null;
}
if (!fns.isNumber(userValue)) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE, MODULE_NAME, JSON.stringify(condition), userValueType, conditionName));
return null;
}
if (!fns.isFinite(userValue)) {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.OUT_OF_BOUNDS, MODULE_NAME, JSON.stringify(condition), conditionName));
return null;
}
return userValue > conditionValue;
}
|
[
"function",
"greaterThanEvaluator",
"(",
"condition",
",",
"userAttributes",
",",
"logger",
")",
"{",
"var",
"conditionName",
"=",
"condition",
".",
"name",
";",
"var",
"userValue",
"=",
"userAttributes",
"[",
"conditionName",
"]",
";",
"var",
"userValueType",
"=",
"typeof",
"userValue",
";",
"var",
"conditionValue",
"=",
"condition",
".",
"value",
";",
"if",
"(",
"!",
"fns",
".",
"isFinite",
"(",
"conditionValue",
")",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNEXPECTED_CONDITION_VALUE",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
")",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"userValue",
"===",
"null",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"DEBUG",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNEXPECTED_TYPE_NULL",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
",",
"conditionName",
")",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"fns",
".",
"isNumber",
"(",
"userValue",
")",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNEXPECTED_TYPE",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
",",
"userValueType",
",",
"conditionName",
")",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"fns",
".",
"isFinite",
"(",
"userValue",
")",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"OUT_OF_BOUNDS",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
",",
"conditionName",
")",
")",
";",
"return",
"null",
";",
"}",
"return",
"userValue",
">",
"conditionValue",
";",
"}"
] |
Evaluate the given greater than match condition for the given user attributes
@param {Object} condition
@param {Object} userAttributes
@param {Object} logger
@returns {?Boolean} true if the user attribute value is greater than the condition value,
false if the user attribute value is less than or equal to the condition value,
null if the condition value isn't a number or the user attribute value
isn't a number
|
[
"Evaluate",
"the",
"given",
"greater",
"than",
"match",
"condition",
"for",
"the",
"given",
"user",
"attributes"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js#L155-L182
|
9,905
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js
|
substringEvaluator
|
function substringEvaluator(condition, userAttributes, logger) {
var conditionName = condition.name;
var userValue = userAttributes[condition.name];
var userValueType = typeof userValue;
var conditionValue = condition.value;
if (typeof conditionValue !== 'string') {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_CONDITION_VALUE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
if (userValue === null) {
logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE_NULL, MODULE_NAME, JSON.stringify(condition), conditionName));
return null;
}
if (typeof userValue !== 'string') {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE, MODULE_NAME, JSON.stringify(condition), userValueType, conditionName));
return null;
}
return userValue.indexOf(conditionValue) !== -1;
}
|
javascript
|
function substringEvaluator(condition, userAttributes, logger) {
var conditionName = condition.name;
var userValue = userAttributes[condition.name];
var userValueType = typeof userValue;
var conditionValue = condition.value;
if (typeof conditionValue !== 'string') {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_CONDITION_VALUE, MODULE_NAME, JSON.stringify(condition)));
return null;
}
if (userValue === null) {
logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE_NULL, MODULE_NAME, JSON.stringify(condition), conditionName));
return null;
}
if (typeof userValue !== 'string') {
logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE, MODULE_NAME, JSON.stringify(condition), userValueType, conditionName));
return null;
}
return userValue.indexOf(conditionValue) !== -1;
}
|
[
"function",
"substringEvaluator",
"(",
"condition",
",",
"userAttributes",
",",
"logger",
")",
"{",
"var",
"conditionName",
"=",
"condition",
".",
"name",
";",
"var",
"userValue",
"=",
"userAttributes",
"[",
"condition",
".",
"name",
"]",
";",
"var",
"userValueType",
"=",
"typeof",
"userValue",
";",
"var",
"conditionValue",
"=",
"condition",
".",
"value",
";",
"if",
"(",
"typeof",
"conditionValue",
"!==",
"'string'",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNEXPECTED_CONDITION_VALUE",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
")",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"userValue",
"===",
"null",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"DEBUG",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNEXPECTED_TYPE_NULL",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
",",
"conditionName",
")",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"typeof",
"userValue",
"!==",
"'string'",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UNEXPECTED_TYPE",
",",
"MODULE_NAME",
",",
"JSON",
".",
"stringify",
"(",
"condition",
")",
",",
"userValueType",
",",
"conditionName",
")",
")",
";",
"return",
"null",
";",
"}",
"return",
"userValue",
".",
"indexOf",
"(",
"conditionValue",
")",
"!==",
"-",
"1",
";",
"}"
] |
Evaluate the given substring match condition for the given user attributes
@param {Object} condition
@param {Object} userAttributes
@param {Object} logger
@returns {?Boolean} true if the condition value is a substring of the user attribute value,
false if the condition value is not a substring of the user attribute value,
null if the condition value isn't a string or the user attribute value
isn't a string
|
[
"Evaluate",
"the",
"given",
"substring",
"match",
"condition",
"for",
"the",
"given",
"user",
"attributes"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/custom_attribute_condition_evaluator/index.js#L233-L255
|
9,906
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/condition_tree_evaluator/index.js
|
evaluate
|
function evaluate(conditions, leafEvaluator) {
if (Array.isArray(conditions)) {
var firstOperator = conditions[0];
var restOfConditions = conditions.slice(1);
if (DEFAULT_OPERATOR_TYPES.indexOf(firstOperator) === -1) {
// Operator to apply is not explicit - assume 'or'
firstOperator = OR_CONDITION;
restOfConditions = conditions;
}
switch (firstOperator) {
case AND_CONDITION:
return andEvaluator(restOfConditions, leafEvaluator);
case NOT_CONDITION:
return notEvaluator(restOfConditions, leafEvaluator);
default: // firstOperator is OR_CONDITION
return orEvaluator(restOfConditions, leafEvaluator);
}
}
var leafCondition = conditions;
return leafEvaluator(leafCondition);
}
|
javascript
|
function evaluate(conditions, leafEvaluator) {
if (Array.isArray(conditions)) {
var firstOperator = conditions[0];
var restOfConditions = conditions.slice(1);
if (DEFAULT_OPERATOR_TYPES.indexOf(firstOperator) === -1) {
// Operator to apply is not explicit - assume 'or'
firstOperator = OR_CONDITION;
restOfConditions = conditions;
}
switch (firstOperator) {
case AND_CONDITION:
return andEvaluator(restOfConditions, leafEvaluator);
case NOT_CONDITION:
return notEvaluator(restOfConditions, leafEvaluator);
default: // firstOperator is OR_CONDITION
return orEvaluator(restOfConditions, leafEvaluator);
}
}
var leafCondition = conditions;
return leafEvaluator(leafCondition);
}
|
[
"function",
"evaluate",
"(",
"conditions",
",",
"leafEvaluator",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"conditions",
")",
")",
"{",
"var",
"firstOperator",
"=",
"conditions",
"[",
"0",
"]",
";",
"var",
"restOfConditions",
"=",
"conditions",
".",
"slice",
"(",
"1",
")",
";",
"if",
"(",
"DEFAULT_OPERATOR_TYPES",
".",
"indexOf",
"(",
"firstOperator",
")",
"===",
"-",
"1",
")",
"{",
"// Operator to apply is not explicit - assume 'or'",
"firstOperator",
"=",
"OR_CONDITION",
";",
"restOfConditions",
"=",
"conditions",
";",
"}",
"switch",
"(",
"firstOperator",
")",
"{",
"case",
"AND_CONDITION",
":",
"return",
"andEvaluator",
"(",
"restOfConditions",
",",
"leafEvaluator",
")",
";",
"case",
"NOT_CONDITION",
":",
"return",
"notEvaluator",
"(",
"restOfConditions",
",",
"leafEvaluator",
")",
";",
"default",
":",
"// firstOperator is OR_CONDITION",
"return",
"orEvaluator",
"(",
"restOfConditions",
",",
"leafEvaluator",
")",
";",
"}",
"}",
"var",
"leafCondition",
"=",
"conditions",
";",
"return",
"leafEvaluator",
"(",
"leafCondition",
")",
";",
"}"
] |
Top level method to evaluate conditions
@param {Array|*} conditions Nested array of and/or conditions, or a single leaf
condition value of any type
Example: ['and', '0', ['or', '1', '2']]
@param {Function} leafEvaluator Function which will be called to evaluate leaf condition
values
@return {?Boolean} Result of evaluating the conditions using the operator
rules and the leaf evaluator. A return value of null
indicates that the conditions are invalid or unable to be
evaluated
|
[
"Top",
"level",
"method",
"to",
"evaluate",
"conditions"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/condition_tree_evaluator/index.js#L35-L58
|
9,907
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/condition_tree_evaluator/index.js
|
andEvaluator
|
function andEvaluator(conditions, leafEvaluator) {
var sawNullResult = false;
for (var i = 0; i < conditions.length; i++) {
var conditionResult = evaluate(conditions[i], leafEvaluator);
if (conditionResult === false) {
return false;
}
if (conditionResult === null) {
sawNullResult = true;
}
}
return sawNullResult ? null : true;
}
|
javascript
|
function andEvaluator(conditions, leafEvaluator) {
var sawNullResult = false;
for (var i = 0; i < conditions.length; i++) {
var conditionResult = evaluate(conditions[i], leafEvaluator);
if (conditionResult === false) {
return false;
}
if (conditionResult === null) {
sawNullResult = true;
}
}
return sawNullResult ? null : true;
}
|
[
"function",
"andEvaluator",
"(",
"conditions",
",",
"leafEvaluator",
")",
"{",
"var",
"sawNullResult",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"conditions",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"conditionResult",
"=",
"evaluate",
"(",
"conditions",
"[",
"i",
"]",
",",
"leafEvaluator",
")",
";",
"if",
"(",
"conditionResult",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"conditionResult",
"===",
"null",
")",
"{",
"sawNullResult",
"=",
"true",
";",
"}",
"}",
"return",
"sawNullResult",
"?",
"null",
":",
"true",
";",
"}"
] |
Evaluates an array of conditions as if the evaluator had been applied
to each entry and the results AND-ed together.
@param {Array} conditions Array of conditions ex: [operand_1, operand_2]
@param {Function} leafEvaluator Function which will be called to evaluate leaf condition values
@return {?Boolean} Result of evaluating the conditions. A return value of null
indicates that the conditions are invalid or unable to be
evaluated.
|
[
"Evaluates",
"an",
"array",
"of",
"conditions",
"as",
"if",
"the",
"evaluator",
"had",
"been",
"applied",
"to",
"each",
"entry",
"and",
"the",
"results",
"AND",
"-",
"ed",
"together",
"."
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/condition_tree_evaluator/index.js#L69-L81
|
9,908
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/condition_tree_evaluator/index.js
|
notEvaluator
|
function notEvaluator(conditions, leafEvaluator) {
if (conditions.length > 0) {
var result = evaluate(conditions[0], leafEvaluator);
return result === null ? null : !result;
}
return null;
}
|
javascript
|
function notEvaluator(conditions, leafEvaluator) {
if (conditions.length > 0) {
var result = evaluate(conditions[0], leafEvaluator);
return result === null ? null : !result;
}
return null;
}
|
[
"function",
"notEvaluator",
"(",
"conditions",
",",
"leafEvaluator",
")",
"{",
"if",
"(",
"conditions",
".",
"length",
">",
"0",
")",
"{",
"var",
"result",
"=",
"evaluate",
"(",
"conditions",
"[",
"0",
"]",
",",
"leafEvaluator",
")",
";",
"return",
"result",
"===",
"null",
"?",
"null",
":",
"!",
"result",
";",
"}",
"return",
"null",
";",
"}"
] |
Evaluates an array of conditions as if the evaluator had been applied
to a single entry and NOT was applied to the result.
@param {Array} conditions Array of conditions ex: [operand_1]
@param {Function} leafEvaluator Function which will be called to evaluate leaf condition values
@return {?Boolean} Result of evaluating the conditions. A return value of null
indicates that the conditions are invalid or unable to be
evaluated.
|
[
"Evaluates",
"an",
"array",
"of",
"conditions",
"as",
"if",
"the",
"evaluator",
"had",
"been",
"applied",
"to",
"a",
"single",
"entry",
"and",
"NOT",
"was",
"applied",
"to",
"the",
"result",
"."
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/condition_tree_evaluator/index.js#L92-L98
|
9,909
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/optimizely/index.js
|
Optimizely
|
function Optimizely(config) {
var clientEngine = config.clientEngine;
if (clientEngine !== enums.NODE_CLIENT_ENGINE && clientEngine !== enums.JAVASCRIPT_CLIENT_ENGINE) {
config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.INVALID_CLIENT_ENGINE, MODULE_NAME, clientEngine));
clientEngine = enums.NODE_CLIENT_ENGINE;
}
this.clientEngine = clientEngine;
this.clientVersion = config.clientVersion || enums.NODE_CLIENT_VERSION;
this.errorHandler = config.errorHandler;
this.eventDispatcher = config.eventDispatcher;
this.__isOptimizelyConfigValid = config.isValidInstance;
this.logger = config.logger;
this.projectConfigManager = new projectConfigManager.ProjectConfigManager({
datafile: config.datafile,
datafileOptions: config.datafileOptions,
jsonSchemaValidator: config.jsonSchemaValidator,
sdkKey: config.sdkKey,
skipJSONValidation: config.skipJSONValidation,
});
this.__disposeOnUpdate = this.projectConfigManager.onUpdate(function(configObj) {
this.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.UPDATED_OPTIMIZELY_CONFIG, MODULE_NAME, configObj.revision, configObj.projectId));
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE);
}.bind(this));
this.__readyPromise = this.projectConfigManager.onReady();
var userProfileService = null;
if (config.userProfileService) {
try {
if (userProfileServiceValidator.validate(config.userProfileService)) {
userProfileService = config.userProfileService;
this.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.VALID_USER_PROFILE_SERVICE, MODULE_NAME));
}
} catch (ex) {
this.logger.log(LOG_LEVEL.WARNING, ex.message);
}
}
this.decisionService = decisionService.createDecisionService({
userProfileService: userProfileService,
logger: this.logger,
});
this.notificationCenter = notificationCenter.createNotificationCenter({
logger: this.logger,
errorHandler: this.errorHandler,
});
this.eventProcessor = new eventProcessor.LogTierV1EventProcessor({
dispatcher: this.eventDispatcher,
flushInterval: config.eventFlushInterval || DEFAULT_EVENT_FLUSH_INTERVAL,
maxQueueSize: config.eventBatchSize || DEFAULT_EVENT_MAX_QUEUE_SIZE,
});
this.eventProcessor.start();
this.__readyTimeouts = {};
this.__nextReadyTimeoutId = 0;
}
|
javascript
|
function Optimizely(config) {
var clientEngine = config.clientEngine;
if (clientEngine !== enums.NODE_CLIENT_ENGINE && clientEngine !== enums.JAVASCRIPT_CLIENT_ENGINE) {
config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.INVALID_CLIENT_ENGINE, MODULE_NAME, clientEngine));
clientEngine = enums.NODE_CLIENT_ENGINE;
}
this.clientEngine = clientEngine;
this.clientVersion = config.clientVersion || enums.NODE_CLIENT_VERSION;
this.errorHandler = config.errorHandler;
this.eventDispatcher = config.eventDispatcher;
this.__isOptimizelyConfigValid = config.isValidInstance;
this.logger = config.logger;
this.projectConfigManager = new projectConfigManager.ProjectConfigManager({
datafile: config.datafile,
datafileOptions: config.datafileOptions,
jsonSchemaValidator: config.jsonSchemaValidator,
sdkKey: config.sdkKey,
skipJSONValidation: config.skipJSONValidation,
});
this.__disposeOnUpdate = this.projectConfigManager.onUpdate(function(configObj) {
this.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.UPDATED_OPTIMIZELY_CONFIG, MODULE_NAME, configObj.revision, configObj.projectId));
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE);
}.bind(this));
this.__readyPromise = this.projectConfigManager.onReady();
var userProfileService = null;
if (config.userProfileService) {
try {
if (userProfileServiceValidator.validate(config.userProfileService)) {
userProfileService = config.userProfileService;
this.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.VALID_USER_PROFILE_SERVICE, MODULE_NAME));
}
} catch (ex) {
this.logger.log(LOG_LEVEL.WARNING, ex.message);
}
}
this.decisionService = decisionService.createDecisionService({
userProfileService: userProfileService,
logger: this.logger,
});
this.notificationCenter = notificationCenter.createNotificationCenter({
logger: this.logger,
errorHandler: this.errorHandler,
});
this.eventProcessor = new eventProcessor.LogTierV1EventProcessor({
dispatcher: this.eventDispatcher,
flushInterval: config.eventFlushInterval || DEFAULT_EVENT_FLUSH_INTERVAL,
maxQueueSize: config.eventBatchSize || DEFAULT_EVENT_MAX_QUEUE_SIZE,
});
this.eventProcessor.start();
this.__readyTimeouts = {};
this.__nextReadyTimeoutId = 0;
}
|
[
"function",
"Optimizely",
"(",
"config",
")",
"{",
"var",
"clientEngine",
"=",
"config",
".",
"clientEngine",
";",
"if",
"(",
"clientEngine",
"!==",
"enums",
".",
"NODE_CLIENT_ENGINE",
"&&",
"clientEngine",
"!==",
"enums",
".",
"JAVASCRIPT_CLIENT_ENGINE",
")",
"{",
"config",
".",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"INFO",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"INVALID_CLIENT_ENGINE",
",",
"MODULE_NAME",
",",
"clientEngine",
")",
")",
";",
"clientEngine",
"=",
"enums",
".",
"NODE_CLIENT_ENGINE",
";",
"}",
"this",
".",
"clientEngine",
"=",
"clientEngine",
";",
"this",
".",
"clientVersion",
"=",
"config",
".",
"clientVersion",
"||",
"enums",
".",
"NODE_CLIENT_VERSION",
";",
"this",
".",
"errorHandler",
"=",
"config",
".",
"errorHandler",
";",
"this",
".",
"eventDispatcher",
"=",
"config",
".",
"eventDispatcher",
";",
"this",
".",
"__isOptimizelyConfigValid",
"=",
"config",
".",
"isValidInstance",
";",
"this",
".",
"logger",
"=",
"config",
".",
"logger",
";",
"this",
".",
"projectConfigManager",
"=",
"new",
"projectConfigManager",
".",
"ProjectConfigManager",
"(",
"{",
"datafile",
":",
"config",
".",
"datafile",
",",
"datafileOptions",
":",
"config",
".",
"datafileOptions",
",",
"jsonSchemaValidator",
":",
"config",
".",
"jsonSchemaValidator",
",",
"sdkKey",
":",
"config",
".",
"sdkKey",
",",
"skipJSONValidation",
":",
"config",
".",
"skipJSONValidation",
",",
"}",
")",
";",
"this",
".",
"__disposeOnUpdate",
"=",
"this",
".",
"projectConfigManager",
".",
"onUpdate",
"(",
"function",
"(",
"configObj",
")",
"{",
"this",
".",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"INFO",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"UPDATED_OPTIMIZELY_CONFIG",
",",
"MODULE_NAME",
",",
"configObj",
".",
"revision",
",",
"configObj",
".",
"projectId",
")",
")",
";",
"this",
".",
"notificationCenter",
".",
"sendNotifications",
"(",
"NOTIFICATION_TYPES",
".",
"OPTIMIZELY_CONFIG_UPDATE",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"__readyPromise",
"=",
"this",
".",
"projectConfigManager",
".",
"onReady",
"(",
")",
";",
"var",
"userProfileService",
"=",
"null",
";",
"if",
"(",
"config",
".",
"userProfileService",
")",
"{",
"try",
"{",
"if",
"(",
"userProfileServiceValidator",
".",
"validate",
"(",
"config",
".",
"userProfileService",
")",
")",
"{",
"userProfileService",
"=",
"config",
".",
"userProfileService",
";",
"this",
".",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"INFO",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"VALID_USER_PROFILE_SERVICE",
",",
"MODULE_NAME",
")",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"this",
".",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"WARNING",
",",
"ex",
".",
"message",
")",
";",
"}",
"}",
"this",
".",
"decisionService",
"=",
"decisionService",
".",
"createDecisionService",
"(",
"{",
"userProfileService",
":",
"userProfileService",
",",
"logger",
":",
"this",
".",
"logger",
",",
"}",
")",
";",
"this",
".",
"notificationCenter",
"=",
"notificationCenter",
".",
"createNotificationCenter",
"(",
"{",
"logger",
":",
"this",
".",
"logger",
",",
"errorHandler",
":",
"this",
".",
"errorHandler",
",",
"}",
")",
";",
"this",
".",
"eventProcessor",
"=",
"new",
"eventProcessor",
".",
"LogTierV1EventProcessor",
"(",
"{",
"dispatcher",
":",
"this",
".",
"eventDispatcher",
",",
"flushInterval",
":",
"config",
".",
"eventFlushInterval",
"||",
"DEFAULT_EVENT_FLUSH_INTERVAL",
",",
"maxQueueSize",
":",
"config",
".",
"eventBatchSize",
"||",
"DEFAULT_EVENT_MAX_QUEUE_SIZE",
",",
"}",
")",
";",
"this",
".",
"eventProcessor",
".",
"start",
"(",
")",
";",
"this",
".",
"__readyTimeouts",
"=",
"{",
"}",
";",
"this",
".",
"__nextReadyTimeoutId",
"=",
"0",
";",
"}"
] |
The Optimizely class
@param {Object} config
@param {string} config.clientEngine
@param {string} config.clientVersion
@param {Object} config.datafile
@param {Object} config.errorHandler
@param {Object} config.eventDispatcher
@param {Object} config.logger
@param {Object} config.skipJSONValidation
@param {Object} config.userProfileService
@param {Object} config.eventBatchSize
@param {Object} config.eventFlushInterval
|
[
"The",
"Optimizely",
"class"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/optimizely/index.js#L59-L119
|
9,910
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/utils/user_profile_service_validator/index.js
|
function(userProfileServiceInstance) {
if (typeof userProfileServiceInstance.lookup !== 'function') {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_USER_PROFILE_SERVICE, MODULE_NAME, 'Missing function \'lookup\''));
} else if (typeof userProfileServiceInstance.save !== 'function') {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_USER_PROFILE_SERVICE, MODULE_NAME, 'Missing function \'save\''));
}
return true;
}
|
javascript
|
function(userProfileServiceInstance) {
if (typeof userProfileServiceInstance.lookup !== 'function') {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_USER_PROFILE_SERVICE, MODULE_NAME, 'Missing function \'lookup\''));
} else if (typeof userProfileServiceInstance.save !== 'function') {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_USER_PROFILE_SERVICE, MODULE_NAME, 'Missing function \'save\''));
}
return true;
}
|
[
"function",
"(",
"userProfileServiceInstance",
")",
"{",
"if",
"(",
"typeof",
"userProfileServiceInstance",
".",
"lookup",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"INVALID_USER_PROFILE_SERVICE",
",",
"MODULE_NAME",
",",
"'Missing function \\'lookup\\''",
")",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"userProfileServiceInstance",
".",
"save",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"INVALID_USER_PROFILE_SERVICE",
",",
"MODULE_NAME",
",",
"'Missing function \\'save\\''",
")",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
Validates user's provided user profile service instance
@param {Object} userProfileServiceInstance
@return {boolean} True if the instance is valid
@throws If the instance is not valid
|
[
"Validates",
"user",
"s",
"provided",
"user",
"profile",
"service",
"instance"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/user_profile_service_validator/index.js#L33-L40
|
|
9,911
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/core/project_config/project_config_manager.js
|
ProjectConfigManager
|
function ProjectConfigManager(config) {
try {
this.__initialize(config);
} catch (ex) {
logger.error(ex);
this.__updateListeners = [];
this.__configObj = null;
this.__readyPromise = Promise.resolve({
success: false,
reason: getErrorMessage(ex, 'Error in initialize'),
});
}
}
|
javascript
|
function ProjectConfigManager(config) {
try {
this.__initialize(config);
} catch (ex) {
logger.error(ex);
this.__updateListeners = [];
this.__configObj = null;
this.__readyPromise = Promise.resolve({
success: false,
reason: getErrorMessage(ex, 'Error in initialize'),
});
}
}
|
[
"function",
"ProjectConfigManager",
"(",
"config",
")",
"{",
"try",
"{",
"this",
".",
"__initialize",
"(",
"config",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"ex",
")",
";",
"this",
".",
"__updateListeners",
"=",
"[",
"]",
";",
"this",
".",
"__configObj",
"=",
"null",
";",
"this",
".",
"__readyPromise",
"=",
"Promise",
".",
"resolve",
"(",
"{",
"success",
":",
"false",
",",
"reason",
":",
"getErrorMessage",
"(",
"ex",
",",
"'Error in initialize'",
")",
",",
"}",
")",
";",
"}",
"}"
] |
ProjectConfigManager provides project config objects via its methods
getConfig and onUpdate. It uses a DatafileManager to fetch datafiles. It is
responsible for parsing and validating datafiles, and converting datafile
JSON objects into project config objects.
@param {Object} config
@param {Object|string=} config.datafile
@param {Object=} config.datafileOptions
@param {Object=} config.jsonSchemaValidator
@param {string=} config.sdkKey
@param {boolean=} config.skipJSONValidation
|
[
"ProjectConfigManager",
"provides",
"project",
"config",
"objects",
"via",
"its",
"methods",
"getConfig",
"and",
"onUpdate",
".",
"It",
"uses",
"a",
"DatafileManager",
"to",
"fetch",
"datafiles",
".",
"It",
"is",
"responsible",
"for",
"parsing",
"and",
"validating",
"datafiles",
"and",
"converting",
"datafile",
"JSON",
"objects",
"into",
"project",
"config",
"objects",
"."
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/project_config_manager.js#L58-L70
|
9,912
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/utils/json_schema_validator/index.js
|
function(jsonSchema, jsonObject) {
if (!jsonSchema) {
throw new Error(sprintf(ERROR_MESSAGES.JSON_SCHEMA_EXPECTED, MODULE_NAME));
}
if (!jsonObject) {
throw new Error(sprintf(ERROR_MESSAGES.NO_JSON_PROVIDED, MODULE_NAME));
}
var result = validate(jsonObject, jsonSchema);
if (result.valid) {
return true;
} else {
if (fns.isArray(result.errors)) {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE, MODULE_NAME, result.errors[0].property, result.errors[0].message));
}
throw new Error(sprintf(ERROR_MESSAGES.INVALID_JSON, MODULE_NAME));
}
}
|
javascript
|
function(jsonSchema, jsonObject) {
if (!jsonSchema) {
throw new Error(sprintf(ERROR_MESSAGES.JSON_SCHEMA_EXPECTED, MODULE_NAME));
}
if (!jsonObject) {
throw new Error(sprintf(ERROR_MESSAGES.NO_JSON_PROVIDED, MODULE_NAME));
}
var result = validate(jsonObject, jsonSchema);
if (result.valid) {
return true;
} else {
if (fns.isArray(result.errors)) {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE, MODULE_NAME, result.errors[0].property, result.errors[0].message));
}
throw new Error(sprintf(ERROR_MESSAGES.INVALID_JSON, MODULE_NAME));
}
}
|
[
"function",
"(",
"jsonSchema",
",",
"jsonObject",
")",
"{",
"if",
"(",
"!",
"jsonSchema",
")",
"{",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"JSON_SCHEMA_EXPECTED",
",",
"MODULE_NAME",
")",
")",
";",
"}",
"if",
"(",
"!",
"jsonObject",
")",
"{",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"NO_JSON_PROVIDED",
",",
"MODULE_NAME",
")",
")",
";",
"}",
"var",
"result",
"=",
"validate",
"(",
"jsonObject",
",",
"jsonSchema",
")",
";",
"if",
"(",
"result",
".",
"valid",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"if",
"(",
"fns",
".",
"isArray",
"(",
"result",
".",
"errors",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"INVALID_DATAFILE",
",",
"MODULE_NAME",
",",
"result",
".",
"errors",
"[",
"0",
"]",
".",
"property",
",",
"result",
".",
"errors",
"[",
"0",
"]",
".",
"message",
")",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"INVALID_JSON",
",",
"MODULE_NAME",
")",
")",
";",
"}",
"}"
] |
Validate the given json object against the specified schema
@param {Object} jsonSchema The json schema to validate against
@param {Object} jsonObject The object to validate against the schema
@return {Boolean} True if the given object is valid
|
[
"Validate",
"the",
"given",
"json",
"object",
"against",
"the",
"specified",
"schema"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/json_schema_validator/index.js#L30-L48
|
|
9,913
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/utils/event_tag_utils/index.js
|
function(eventTags, logger) {
if (eventTags && eventTags.hasOwnProperty(REVENUE_EVENT_METRIC_NAME)) {
var rawValue = eventTags[REVENUE_EVENT_METRIC_NAME];
var parsedRevenueValue = parseInt(rawValue, 10);
if (isNaN(parsedRevenueValue)) {
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.FAILED_TO_PARSE_REVENUE, MODULE_NAME, rawValue));
return null;
}
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.PARSED_REVENUE_VALUE, MODULE_NAME, parsedRevenueValue));
return parsedRevenueValue;
}
return null;
}
|
javascript
|
function(eventTags, logger) {
if (eventTags && eventTags.hasOwnProperty(REVENUE_EVENT_METRIC_NAME)) {
var rawValue = eventTags[REVENUE_EVENT_METRIC_NAME];
var parsedRevenueValue = parseInt(rawValue, 10);
if (isNaN(parsedRevenueValue)) {
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.FAILED_TO_PARSE_REVENUE, MODULE_NAME, rawValue));
return null;
}
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.PARSED_REVENUE_VALUE, MODULE_NAME, parsedRevenueValue));
return parsedRevenueValue;
}
return null;
}
|
[
"function",
"(",
"eventTags",
",",
"logger",
")",
"{",
"if",
"(",
"eventTags",
"&&",
"eventTags",
".",
"hasOwnProperty",
"(",
"REVENUE_EVENT_METRIC_NAME",
")",
")",
"{",
"var",
"rawValue",
"=",
"eventTags",
"[",
"REVENUE_EVENT_METRIC_NAME",
"]",
";",
"var",
"parsedRevenueValue",
"=",
"parseInt",
"(",
"rawValue",
",",
"10",
")",
";",
"if",
"(",
"isNaN",
"(",
"parsedRevenueValue",
")",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"INFO",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"FAILED_TO_PARSE_REVENUE",
",",
"MODULE_NAME",
",",
"rawValue",
")",
")",
";",
"return",
"null",
";",
"}",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"INFO",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"PARSED_REVENUE_VALUE",
",",
"MODULE_NAME",
",",
"parsedRevenueValue",
")",
")",
";",
"return",
"parsedRevenueValue",
";",
"}",
"return",
"null",
";",
"}"
] |
Grab the revenue value from the event tags. "revenue" is a reserved keyword.
@param {Object} eventTags
@param {Object} logger
@return {Integer|null}
|
[
"Grab",
"the",
"revenue",
"value",
"from",
"the",
"event",
"tags",
".",
"revenue",
"is",
"a",
"reserved",
"keyword",
"."
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/event_tag_utils/index.js#L36-L48
|
|
9,914
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/utils/event_tag_utils/index.js
|
function(eventTags, logger) {
if (eventTags && eventTags.hasOwnProperty(VALUE_EVENT_METRIC_NAME)) {
var rawValue = eventTags[VALUE_EVENT_METRIC_NAME];
var parsedEventValue = parseFloat(rawValue);
if (isNaN(parsedEventValue)) {
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.FAILED_TO_PARSE_VALUE, MODULE_NAME, rawValue));
return null;
}
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.PARSED_NUMERIC_VALUE, MODULE_NAME, parsedEventValue));
return parsedEventValue;
}
return null;
}
|
javascript
|
function(eventTags, logger) {
if (eventTags && eventTags.hasOwnProperty(VALUE_EVENT_METRIC_NAME)) {
var rawValue = eventTags[VALUE_EVENT_METRIC_NAME];
var parsedEventValue = parseFloat(rawValue);
if (isNaN(parsedEventValue)) {
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.FAILED_TO_PARSE_VALUE, MODULE_NAME, rawValue));
return null;
}
logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.PARSED_NUMERIC_VALUE, MODULE_NAME, parsedEventValue));
return parsedEventValue;
}
return null;
}
|
[
"function",
"(",
"eventTags",
",",
"logger",
")",
"{",
"if",
"(",
"eventTags",
"&&",
"eventTags",
".",
"hasOwnProperty",
"(",
"VALUE_EVENT_METRIC_NAME",
")",
")",
"{",
"var",
"rawValue",
"=",
"eventTags",
"[",
"VALUE_EVENT_METRIC_NAME",
"]",
";",
"var",
"parsedEventValue",
"=",
"parseFloat",
"(",
"rawValue",
")",
";",
"if",
"(",
"isNaN",
"(",
"parsedEventValue",
")",
")",
"{",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"INFO",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"FAILED_TO_PARSE_VALUE",
",",
"MODULE_NAME",
",",
"rawValue",
")",
")",
";",
"return",
"null",
";",
"}",
"logger",
".",
"log",
"(",
"LOG_LEVEL",
".",
"INFO",
",",
"sprintf",
"(",
"LOG_MESSAGES",
".",
"PARSED_NUMERIC_VALUE",
",",
"MODULE_NAME",
",",
"parsedEventValue",
")",
")",
";",
"return",
"parsedEventValue",
";",
"}",
"return",
"null",
";",
"}"
] |
Grab the event value from the event tags. "value" is a reserved keyword.
@param {Object} eventTags
@param {Object} logger
@return {Number|null}
|
[
"Grab",
"the",
"event",
"value",
"from",
"the",
"event",
"tags",
".",
"value",
"is",
"a",
"reserved",
"keyword",
"."
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/event_tag_utils/index.js#L56-L68
|
|
9,915
|
optimizely/javascript-sdk
|
packages/optimizely-sdk/lib/utils/attributes_validator/index.js
|
function(attributes) {
if (typeof attributes === 'object' && !Array.isArray(attributes) && attributes !== null) {
lodashForOwn(attributes, function(value, key) {
if (typeof value === 'undefined') {
throw new Error(sprintf(ERROR_MESSAGES.UNDEFINED_ATTRIBUTE, MODULE_NAME, key));
}
});
return true;
} else {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_ATTRIBUTES, MODULE_NAME));
}
}
|
javascript
|
function(attributes) {
if (typeof attributes === 'object' && !Array.isArray(attributes) && attributes !== null) {
lodashForOwn(attributes, function(value, key) {
if (typeof value === 'undefined') {
throw new Error(sprintf(ERROR_MESSAGES.UNDEFINED_ATTRIBUTE, MODULE_NAME, key));
}
});
return true;
} else {
throw new Error(sprintf(ERROR_MESSAGES.INVALID_ATTRIBUTES, MODULE_NAME));
}
}
|
[
"function",
"(",
"attributes",
")",
"{",
"if",
"(",
"typeof",
"attributes",
"===",
"'object'",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"attributes",
")",
"&&",
"attributes",
"!==",
"null",
")",
"{",
"lodashForOwn",
"(",
"attributes",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'undefined'",
")",
"{",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"UNDEFINED_ATTRIBUTE",
",",
"MODULE_NAME",
",",
"key",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"ERROR_MESSAGES",
".",
"INVALID_ATTRIBUTES",
",",
"MODULE_NAME",
")",
")",
";",
"}",
"}"
] |
Validates user's provided attributes
@param {Object} attributes
@return {boolean} True if the attributes are valid
@throws If the attributes are not valid
|
[
"Validates",
"user",
"s",
"provided",
"attributes"
] |
39c3b2d97388100abd1c25d355a71c72b17363be
|
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/attributes_validator/index.js#L35-L46
|
|
9,916
|
qTip2/qTip2
|
src/tips/tips.js
|
function(corner, size, scale) {
scale = scale || 1;
size = size || this.size;
var width = size[0] * scale,
height = size[1] * scale,
width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2),
// Define tip coordinates in terms of height and width values
tips = {
br: [0,0, width,height, width,0],
bl: [0,0, width,0, 0,height],
tr: [0,height, width,0, width,height],
tl: [0,0, 0,height, width,height],
tc: [0,height, width2,0, width,height],
bc: [0,0, width,0, width2,height],
rc: [0,0, width,height2, 0,height],
lc: [width,0, width,height, 0,height2]
};
// Set common side shapes
tips.lt = tips.br; tips.rt = tips.bl;
tips.lb = tips.tr; tips.rb = tips.tl;
return tips[ corner.abbrev() ];
}
|
javascript
|
function(corner, size, scale) {
scale = scale || 1;
size = size || this.size;
var width = size[0] * scale,
height = size[1] * scale,
width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2),
// Define tip coordinates in terms of height and width values
tips = {
br: [0,0, width,height, width,0],
bl: [0,0, width,0, 0,height],
tr: [0,height, width,0, width,height],
tl: [0,0, 0,height, width,height],
tc: [0,height, width2,0, width,height],
bc: [0,0, width,0, width2,height],
rc: [0,0, width,height2, 0,height],
lc: [width,0, width,height, 0,height2]
};
// Set common side shapes
tips.lt = tips.br; tips.rt = tips.bl;
tips.lb = tips.tr; tips.rb = tips.tl;
return tips[ corner.abbrev() ];
}
|
[
"function",
"(",
"corner",
",",
"size",
",",
"scale",
")",
"{",
"scale",
"=",
"scale",
"||",
"1",
";",
"size",
"=",
"size",
"||",
"this",
".",
"size",
";",
"var",
"width",
"=",
"size",
"[",
"0",
"]",
"*",
"scale",
",",
"height",
"=",
"size",
"[",
"1",
"]",
"*",
"scale",
",",
"width2",
"=",
"Math",
".",
"ceil",
"(",
"width",
"/",
"2",
")",
",",
"height2",
"=",
"Math",
".",
"ceil",
"(",
"height",
"/",
"2",
")",
",",
"// Define tip coordinates in terms of height and width values",
"tips",
"=",
"{",
"br",
":",
"[",
"0",
",",
"0",
",",
"width",
",",
"height",
",",
"width",
",",
"0",
"]",
",",
"bl",
":",
"[",
"0",
",",
"0",
",",
"width",
",",
"0",
",",
"0",
",",
"height",
"]",
",",
"tr",
":",
"[",
"0",
",",
"height",
",",
"width",
",",
"0",
",",
"width",
",",
"height",
"]",
",",
"tl",
":",
"[",
"0",
",",
"0",
",",
"0",
",",
"height",
",",
"width",
",",
"height",
"]",
",",
"tc",
":",
"[",
"0",
",",
"height",
",",
"width2",
",",
"0",
",",
"width",
",",
"height",
"]",
",",
"bc",
":",
"[",
"0",
",",
"0",
",",
"width",
",",
"0",
",",
"width2",
",",
"height",
"]",
",",
"rc",
":",
"[",
"0",
",",
"0",
",",
"width",
",",
"height2",
",",
"0",
",",
"height",
"]",
",",
"lc",
":",
"[",
"width",
",",
"0",
",",
"width",
",",
"height",
",",
"0",
",",
"height2",
"]",
"}",
";",
"// Set common side shapes",
"tips",
".",
"lt",
"=",
"tips",
".",
"br",
";",
"tips",
".",
"rt",
"=",
"tips",
".",
"bl",
";",
"tips",
".",
"lb",
"=",
"tips",
".",
"tr",
";",
"tips",
".",
"rb",
"=",
"tips",
".",
"tl",
";",
"return",
"tips",
"[",
"corner",
".",
"abbrev",
"(",
")",
"]",
";",
"}"
] |
Tip coordinates calculator
|
[
"Tip",
"coordinates",
"calculator"
] |
eeffdbaa2340de54f8fb9f0dd0d17532f907be55
|
https://github.com/qTip2/qTip2/blob/eeffdbaa2340de54f8fb9f0dd0d17532f907be55/src/tips/tips.js#L222-L247
|
|
9,917
|
qTip2/qTip2
|
dist/jquery.qtip.js
|
function() {
if(!this.rendered) { return; }
// Set tracking flag
var posOptions = this.options.position;
this.tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse);
// Reassign events
this._unassignEvents();
this._assignEvents();
}
|
javascript
|
function() {
if(!this.rendered) { return; }
// Set tracking flag
var posOptions = this.options.position;
this.tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse);
// Reassign events
this._unassignEvents();
this._assignEvents();
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"rendered",
")",
"{",
"return",
";",
"}",
"// Set tracking flag",
"var",
"posOptions",
"=",
"this",
".",
"options",
".",
"position",
";",
"this",
".",
"tooltip",
".",
"attr",
"(",
"'tracking'",
",",
"posOptions",
".",
"target",
"===",
"'mouse'",
"&&",
"posOptions",
".",
"adjust",
".",
"mouse",
")",
";",
"// Reassign events",
"this",
".",
"_unassignEvents",
"(",
")",
";",
"this",
".",
"_assignEvents",
"(",
")",
";",
"}"
] |
Properties which require event reassignment
|
[
"Properties",
"which",
"require",
"event",
"reassignment"
] |
eeffdbaa2340de54f8fb9f0dd0d17532f907be55
|
https://github.com/qTip2/qTip2/blob/eeffdbaa2340de54f8fb9f0dd0d17532f907be55/dist/jquery.qtip.js#L483-L493
|
|
9,918
|
qTip2/qTip2
|
dist/jquery.qtip.js
|
convertNotation
|
function convertNotation(options, notation) {
var i = 0, obj, option = options,
// Split notation into array
levels = notation.split('.');
// Loop through
while(option = option[ levels[i++] ]) {
if(i < levels.length) { obj = option; }
}
return [obj || options, levels.pop()];
}
|
javascript
|
function convertNotation(options, notation) {
var i = 0, obj, option = options,
// Split notation into array
levels = notation.split('.');
// Loop through
while(option = option[ levels[i++] ]) {
if(i < levels.length) { obj = option; }
}
return [obj || options, levels.pop()];
}
|
[
"function",
"convertNotation",
"(",
"options",
",",
"notation",
")",
"{",
"var",
"i",
"=",
"0",
",",
"obj",
",",
"option",
"=",
"options",
",",
"// Split notation into array",
"levels",
"=",
"notation",
".",
"split",
"(",
"'.'",
")",
";",
"// Loop through",
"while",
"(",
"option",
"=",
"option",
"[",
"levels",
"[",
"i",
"++",
"]",
"]",
")",
"{",
"if",
"(",
"i",
"<",
"levels",
".",
"length",
")",
"{",
"obj",
"=",
"option",
";",
"}",
"}",
"return",
"[",
"obj",
"||",
"options",
",",
"levels",
".",
"pop",
"(",
")",
"]",
";",
"}"
] |
Dot notation converter
|
[
"Dot",
"notation",
"converter"
] |
eeffdbaa2340de54f8fb9f0dd0d17532f907be55
|
https://github.com/qTip2/qTip2/blob/eeffdbaa2340de54f8fb9f0dd0d17532f907be55/dist/jquery.qtip.js#L498-L510
|
9,919
|
qTip2/qTip2
|
dist/jquery.qtip.js
|
delegate
|
function delegate(selector, events, method) {
$(document.body).delegate(selector,
(events.split ? events : events.join('.'+NAMESPACE + ' ')) + '.'+NAMESPACE,
function() {
var api = QTIP.api[ $.attr(this, ATTR_ID) ];
api && !api.disabled && method.apply(api, arguments);
}
);
}
|
javascript
|
function delegate(selector, events, method) {
$(document.body).delegate(selector,
(events.split ? events : events.join('.'+NAMESPACE + ' ')) + '.'+NAMESPACE,
function() {
var api = QTIP.api[ $.attr(this, ATTR_ID) ];
api && !api.disabled && method.apply(api, arguments);
}
);
}
|
[
"function",
"delegate",
"(",
"selector",
",",
"events",
",",
"method",
")",
"{",
"$",
"(",
"document",
".",
"body",
")",
".",
"delegate",
"(",
"selector",
",",
"(",
"events",
".",
"split",
"?",
"events",
":",
"events",
".",
"join",
"(",
"'.'",
"+",
"NAMESPACE",
"+",
"' '",
")",
")",
"+",
"'.'",
"+",
"NAMESPACE",
",",
"function",
"(",
")",
"{",
"var",
"api",
"=",
"QTIP",
".",
"api",
"[",
"$",
".",
"attr",
"(",
"this",
",",
"ATTR_ID",
")",
"]",
";",
"api",
"&&",
"!",
"api",
".",
"disabled",
"&&",
"method",
".",
"apply",
"(",
"api",
",",
"arguments",
")",
";",
"}",
")",
";",
"}"
] |
Global delegation helper
|
[
"Global",
"delegation",
"helper"
] |
eeffdbaa2340de54f8fb9f0dd0d17532f907be55
|
https://github.com/qTip2/qTip2/blob/eeffdbaa2340de54f8fb9f0dd0d17532f907be55/dist/jquery.qtip.js#L1399-L1407
|
9,920
|
qTip2/qTip2
|
dist/jquery.qtip.js
|
hoverIntent
|
function hoverIntent(hoverEvent) {
// Only continue if tooltip isn't disabled
if(this.disabled || this.destroyed) { return FALSE; }
// Cache the event data
this.cache.event = hoverEvent && $.event.fix(hoverEvent);
this.cache.target = hoverEvent && $(hoverEvent.target);
// Start the event sequence
clearTimeout(this.timers.show);
this.timers.show = delay.call(this,
function() { this.render(typeof hoverEvent === 'object' || options.show.ready); },
options.prerender ? 0 : options.show.delay
);
}
|
javascript
|
function hoverIntent(hoverEvent) {
// Only continue if tooltip isn't disabled
if(this.disabled || this.destroyed) { return FALSE; }
// Cache the event data
this.cache.event = hoverEvent && $.event.fix(hoverEvent);
this.cache.target = hoverEvent && $(hoverEvent.target);
// Start the event sequence
clearTimeout(this.timers.show);
this.timers.show = delay.call(this,
function() { this.render(typeof hoverEvent === 'object' || options.show.ready); },
options.prerender ? 0 : options.show.delay
);
}
|
[
"function",
"hoverIntent",
"(",
"hoverEvent",
")",
"{",
"// Only continue if tooltip isn't disabled",
"if",
"(",
"this",
".",
"disabled",
"||",
"this",
".",
"destroyed",
")",
"{",
"return",
"FALSE",
";",
"}",
"// Cache the event data",
"this",
".",
"cache",
".",
"event",
"=",
"hoverEvent",
"&&",
"$",
".",
"event",
".",
"fix",
"(",
"hoverEvent",
")",
";",
"this",
".",
"cache",
".",
"target",
"=",
"hoverEvent",
"&&",
"$",
"(",
"hoverEvent",
".",
"target",
")",
";",
"// Start the event sequence",
"clearTimeout",
"(",
"this",
".",
"timers",
".",
"show",
")",
";",
"this",
".",
"timers",
".",
"show",
"=",
"delay",
".",
"call",
"(",
"this",
",",
"function",
"(",
")",
"{",
"this",
".",
"render",
"(",
"typeof",
"hoverEvent",
"===",
"'object'",
"||",
"options",
".",
"show",
".",
"ready",
")",
";",
"}",
",",
"options",
".",
"prerender",
"?",
"0",
":",
"options",
".",
"show",
".",
"delay",
")",
";",
"}"
] |
Define hoverIntent function
|
[
"Define",
"hoverIntent",
"function"
] |
eeffdbaa2340de54f8fb9f0dd0d17532f907be55
|
https://github.com/qTip2/qTip2/blob/eeffdbaa2340de54f8fb9f0dd0d17532f907be55/dist/jquery.qtip.js#L1487-L1501
|
9,921
|
qTip2/qTip2
|
dist/jquery.qtip.js
|
stealFocus
|
function stealFocus(event) {
if(!elem.is(':visible')) { return; }
var target = $(event.target),
tooltip = current.tooltip,
container = target.closest(SELECTOR),
targetOnTop;
// Determine if input container target is above this
targetOnTop = container.length < 1 ? FALSE :
parseInt(container[0].style.zIndex, 10) > parseInt(tooltip[0].style.zIndex, 10);
// If we're showing a modal, but focus has landed on an input below
// this modal, divert focus to the first visible input in this modal
// or if we can't find one... the tooltip itself
if(!targetOnTop && target.closest(SELECTOR)[0] !== tooltip[0]) {
focusInputs(target);
}
}
|
javascript
|
function stealFocus(event) {
if(!elem.is(':visible')) { return; }
var target = $(event.target),
tooltip = current.tooltip,
container = target.closest(SELECTOR),
targetOnTop;
// Determine if input container target is above this
targetOnTop = container.length < 1 ? FALSE :
parseInt(container[0].style.zIndex, 10) > parseInt(tooltip[0].style.zIndex, 10);
// If we're showing a modal, but focus has landed on an input below
// this modal, divert focus to the first visible input in this modal
// or if we can't find one... the tooltip itself
if(!targetOnTop && target.closest(SELECTOR)[0] !== tooltip[0]) {
focusInputs(target);
}
}
|
[
"function",
"stealFocus",
"(",
"event",
")",
"{",
"if",
"(",
"!",
"elem",
".",
"is",
"(",
"':visible'",
")",
")",
"{",
"return",
";",
"}",
"var",
"target",
"=",
"$",
"(",
"event",
".",
"target",
")",
",",
"tooltip",
"=",
"current",
".",
"tooltip",
",",
"container",
"=",
"target",
".",
"closest",
"(",
"SELECTOR",
")",
",",
"targetOnTop",
";",
"// Determine if input container target is above this",
"targetOnTop",
"=",
"container",
".",
"length",
"<",
"1",
"?",
"FALSE",
":",
"parseInt",
"(",
"container",
"[",
"0",
"]",
".",
"style",
".",
"zIndex",
",",
"10",
")",
">",
"parseInt",
"(",
"tooltip",
"[",
"0",
"]",
".",
"style",
".",
"zIndex",
",",
"10",
")",
";",
"// If we're showing a modal, but focus has landed on an input below",
"// this modal, divert focus to the first visible input in this modal",
"// or if we can't find one... the tooltip itself",
"if",
"(",
"!",
"targetOnTop",
"&&",
"target",
".",
"closest",
"(",
"SELECTOR",
")",
"[",
"0",
"]",
"!==",
"tooltip",
"[",
"0",
"]",
")",
"{",
"focusInputs",
"(",
"target",
")",
";",
"}",
"}"
] |
Steal focus from elements outside tooltip
|
[
"Steal",
"focus",
"from",
"elements",
"outside",
"tooltip"
] |
eeffdbaa2340de54f8fb9f0dd0d17532f907be55
|
https://github.com/qTip2/qTip2/blob/eeffdbaa2340de54f8fb9f0dd0d17532f907be55/dist/jquery.qtip.js#L2701-L2719
|
9,922
|
qTip2/qTip2
|
dist/jquery.qtip.js
|
calculate
|
function calculate(side, otherSide, type, adjustment, side1, side2, lengthName, targetLength, elemLength) {
var initialPos = position[side1],
mySide = my[side],
atSide = at[side],
isShift = type === SHIFT,
myLength = mySide === side1 ? elemLength : mySide === side2 ? -elemLength : -elemLength / 2,
atLength = atSide === side1 ? targetLength : atSide === side2 ? -targetLength : -targetLength / 2,
sideOffset = viewportScroll[side1] + viewportOffset[side1] - (containerStatic ? 0 : containerOffset[side1]),
overflow1 = sideOffset - initialPos,
overflow2 = initialPos + elemLength - (lengthName === WIDTH ? viewportWidth : viewportHeight) - sideOffset,
offset = myLength - (my.precedance === side || mySide === my[otherSide] ? atLength : 0) - (atSide === CENTER ? targetLength / 2 : 0);
// shift
if(isShift) {
offset = (mySide === side1 ? 1 : -1) * myLength;
// Adjust position but keep it within viewport dimensions
position[side1] += overflow1 > 0 ? overflow1 : overflow2 > 0 ? -overflow2 : 0;
position[side1] = Math.max(
-containerOffset[side1] + viewportOffset[side1],
initialPos - offset,
Math.min(
Math.max(
-containerOffset[side1] + viewportOffset[side1] + (lengthName === WIDTH ? viewportWidth : viewportHeight),
initialPos + offset
),
position[side1],
// Make sure we don't adjust complete off the element when using 'center'
mySide === 'center' ? initialPos - myLength : 1E9
)
);
}
// flip/flipinvert
else {
// Update adjustment amount depending on if using flipinvert or flip
adjustment *= type === FLIPINVERT ? 2 : 0;
// Check for overflow on the left/top
if(overflow1 > 0 && (mySide !== side1 || overflow2 > 0)) {
position[side1] -= offset + adjustment;
newMy.invert(side, side1);
}
// Check for overflow on the bottom/right
else if(overflow2 > 0 && (mySide !== side2 || overflow1 > 0) ) {
position[side1] -= (mySide === CENTER ? -offset : offset) + adjustment;
newMy.invert(side, side2);
}
// Make sure we haven't made things worse with the adjustment and reset if so
if(position[side1] < viewportScroll[side1] && -position[side1] > overflow2) {
position[side1] = initialPos; newMy = my.clone();
}
}
return position[side1] - initialPos;
}
|
javascript
|
function calculate(side, otherSide, type, adjustment, side1, side2, lengthName, targetLength, elemLength) {
var initialPos = position[side1],
mySide = my[side],
atSide = at[side],
isShift = type === SHIFT,
myLength = mySide === side1 ? elemLength : mySide === side2 ? -elemLength : -elemLength / 2,
atLength = atSide === side1 ? targetLength : atSide === side2 ? -targetLength : -targetLength / 2,
sideOffset = viewportScroll[side1] + viewportOffset[side1] - (containerStatic ? 0 : containerOffset[side1]),
overflow1 = sideOffset - initialPos,
overflow2 = initialPos + elemLength - (lengthName === WIDTH ? viewportWidth : viewportHeight) - sideOffset,
offset = myLength - (my.precedance === side || mySide === my[otherSide] ? atLength : 0) - (atSide === CENTER ? targetLength / 2 : 0);
// shift
if(isShift) {
offset = (mySide === side1 ? 1 : -1) * myLength;
// Adjust position but keep it within viewport dimensions
position[side1] += overflow1 > 0 ? overflow1 : overflow2 > 0 ? -overflow2 : 0;
position[side1] = Math.max(
-containerOffset[side1] + viewportOffset[side1],
initialPos - offset,
Math.min(
Math.max(
-containerOffset[side1] + viewportOffset[side1] + (lengthName === WIDTH ? viewportWidth : viewportHeight),
initialPos + offset
),
position[side1],
// Make sure we don't adjust complete off the element when using 'center'
mySide === 'center' ? initialPos - myLength : 1E9
)
);
}
// flip/flipinvert
else {
// Update adjustment amount depending on if using flipinvert or flip
adjustment *= type === FLIPINVERT ? 2 : 0;
// Check for overflow on the left/top
if(overflow1 > 0 && (mySide !== side1 || overflow2 > 0)) {
position[side1] -= offset + adjustment;
newMy.invert(side, side1);
}
// Check for overflow on the bottom/right
else if(overflow2 > 0 && (mySide !== side2 || overflow1 > 0) ) {
position[side1] -= (mySide === CENTER ? -offset : offset) + adjustment;
newMy.invert(side, side2);
}
// Make sure we haven't made things worse with the adjustment and reset if so
if(position[side1] < viewportScroll[side1] && -position[side1] > overflow2) {
position[side1] = initialPos; newMy = my.clone();
}
}
return position[side1] - initialPos;
}
|
[
"function",
"calculate",
"(",
"side",
",",
"otherSide",
",",
"type",
",",
"adjustment",
",",
"side1",
",",
"side2",
",",
"lengthName",
",",
"targetLength",
",",
"elemLength",
")",
"{",
"var",
"initialPos",
"=",
"position",
"[",
"side1",
"]",
",",
"mySide",
"=",
"my",
"[",
"side",
"]",
",",
"atSide",
"=",
"at",
"[",
"side",
"]",
",",
"isShift",
"=",
"type",
"===",
"SHIFT",
",",
"myLength",
"=",
"mySide",
"===",
"side1",
"?",
"elemLength",
":",
"mySide",
"===",
"side2",
"?",
"-",
"elemLength",
":",
"-",
"elemLength",
"/",
"2",
",",
"atLength",
"=",
"atSide",
"===",
"side1",
"?",
"targetLength",
":",
"atSide",
"===",
"side2",
"?",
"-",
"targetLength",
":",
"-",
"targetLength",
"/",
"2",
",",
"sideOffset",
"=",
"viewportScroll",
"[",
"side1",
"]",
"+",
"viewportOffset",
"[",
"side1",
"]",
"-",
"(",
"containerStatic",
"?",
"0",
":",
"containerOffset",
"[",
"side1",
"]",
")",
",",
"overflow1",
"=",
"sideOffset",
"-",
"initialPos",
",",
"overflow2",
"=",
"initialPos",
"+",
"elemLength",
"-",
"(",
"lengthName",
"===",
"WIDTH",
"?",
"viewportWidth",
":",
"viewportHeight",
")",
"-",
"sideOffset",
",",
"offset",
"=",
"myLength",
"-",
"(",
"my",
".",
"precedance",
"===",
"side",
"||",
"mySide",
"===",
"my",
"[",
"otherSide",
"]",
"?",
"atLength",
":",
"0",
")",
"-",
"(",
"atSide",
"===",
"CENTER",
"?",
"targetLength",
"/",
"2",
":",
"0",
")",
";",
"// shift",
"if",
"(",
"isShift",
")",
"{",
"offset",
"=",
"(",
"mySide",
"===",
"side1",
"?",
"1",
":",
"-",
"1",
")",
"*",
"myLength",
";",
"// Adjust position but keep it within viewport dimensions",
"position",
"[",
"side1",
"]",
"+=",
"overflow1",
">",
"0",
"?",
"overflow1",
":",
"overflow2",
">",
"0",
"?",
"-",
"overflow2",
":",
"0",
";",
"position",
"[",
"side1",
"]",
"=",
"Math",
".",
"max",
"(",
"-",
"containerOffset",
"[",
"side1",
"]",
"+",
"viewportOffset",
"[",
"side1",
"]",
",",
"initialPos",
"-",
"offset",
",",
"Math",
".",
"min",
"(",
"Math",
".",
"max",
"(",
"-",
"containerOffset",
"[",
"side1",
"]",
"+",
"viewportOffset",
"[",
"side1",
"]",
"+",
"(",
"lengthName",
"===",
"WIDTH",
"?",
"viewportWidth",
":",
"viewportHeight",
")",
",",
"initialPos",
"+",
"offset",
")",
",",
"position",
"[",
"side1",
"]",
",",
"// Make sure we don't adjust complete off the element when using 'center'",
"mySide",
"===",
"'center'",
"?",
"initialPos",
"-",
"myLength",
":",
"1E9",
")",
")",
";",
"}",
"// flip/flipinvert",
"else",
"{",
"// Update adjustment amount depending on if using flipinvert or flip",
"adjustment",
"*=",
"type",
"===",
"FLIPINVERT",
"?",
"2",
":",
"0",
";",
"// Check for overflow on the left/top",
"if",
"(",
"overflow1",
">",
"0",
"&&",
"(",
"mySide",
"!==",
"side1",
"||",
"overflow2",
">",
"0",
")",
")",
"{",
"position",
"[",
"side1",
"]",
"-=",
"offset",
"+",
"adjustment",
";",
"newMy",
".",
"invert",
"(",
"side",
",",
"side1",
")",
";",
"}",
"// Check for overflow on the bottom/right",
"else",
"if",
"(",
"overflow2",
">",
"0",
"&&",
"(",
"mySide",
"!==",
"side2",
"||",
"overflow1",
">",
"0",
")",
")",
"{",
"position",
"[",
"side1",
"]",
"-=",
"(",
"mySide",
"===",
"CENTER",
"?",
"-",
"offset",
":",
"offset",
")",
"+",
"adjustment",
";",
"newMy",
".",
"invert",
"(",
"side",
",",
"side2",
")",
";",
"}",
"// Make sure we haven't made things worse with the adjustment and reset if so",
"if",
"(",
"position",
"[",
"side1",
"]",
"<",
"viewportScroll",
"[",
"side1",
"]",
"&&",
"-",
"position",
"[",
"side1",
"]",
">",
"overflow2",
")",
"{",
"position",
"[",
"side1",
"]",
"=",
"initialPos",
";",
"newMy",
"=",
"my",
".",
"clone",
"(",
")",
";",
"}",
"}",
"return",
"position",
"[",
"side1",
"]",
"-",
"initialPos",
";",
"}"
] |
Generic calculation method
|
[
"Generic",
"calculation",
"method"
] |
eeffdbaa2340de54f8fb9f0dd0d17532f907be55
|
https://github.com/qTip2/qTip2/blob/eeffdbaa2340de54f8fb9f0dd0d17532f907be55/dist/jquery.qtip.js#L3022-L3081
|
9,923
|
mozilla/node-client-sessions
|
lib/client-sessions.js
|
zeroBuffer
|
function zeroBuffer(buf) {
for (var i = 0; i < buf.length; i++) {
buf[i] = 0;
}
return buf;
}
|
javascript
|
function zeroBuffer(buf) {
for (var i = 0; i < buf.length; i++) {
buf[i] = 0;
}
return buf;
}
|
[
"function",
"zeroBuffer",
"(",
"buf",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"buf",
".",
"length",
";",
"i",
"++",
")",
"{",
"buf",
"[",
"i",
"]",
"=",
"0",
";",
"}",
"return",
"buf",
";",
"}"
] |
it's good cryptographic pracitice to not leave buffers with sensitive contents hanging around.
|
[
"it",
"s",
"good",
"cryptographic",
"pracitice",
"to",
"not",
"leave",
"buffers",
"with",
"sensitive",
"contents",
"hanging",
"around",
"."
] |
b621a4ad49cf517ae43d6060f4ceb8306ac22506
|
https://github.com/mozilla/node-client-sessions/blob/b621a4ad49cf517ae43d6060f4ceb8306ac22506/lib/client-sessions.js#L148-L153
|
9,924
|
GetStream/stream-js
|
src/lib/errors.js
|
ErrorAbstract
|
function ErrorAbstract(msg, constructor) {
this.message = msg;
Error.call(this, this.message);
/* istanbul ignore else */
if (canCapture) {
Error.captureStackTrace(this, constructor);
} else if (canStack) {
this.stack = new Error().stack;
} else {
this.stack = '';
}
}
|
javascript
|
function ErrorAbstract(msg, constructor) {
this.message = msg;
Error.call(this, this.message);
/* istanbul ignore else */
if (canCapture) {
Error.captureStackTrace(this, constructor);
} else if (canStack) {
this.stack = new Error().stack;
} else {
this.stack = '';
}
}
|
[
"function",
"ErrorAbstract",
"(",
"msg",
",",
"constructor",
")",
"{",
"this",
".",
"message",
"=",
"msg",
";",
"Error",
".",
"call",
"(",
"this",
",",
"this",
".",
"message",
")",
";",
"/* istanbul ignore else */",
"if",
"(",
"canCapture",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"constructor",
")",
";",
"}",
"else",
"if",
"(",
"canStack",
")",
"{",
"this",
".",
"stack",
"=",
"new",
"Error",
"(",
")",
".",
"stack",
";",
"}",
"else",
"{",
"this",
".",
"stack",
"=",
"''",
";",
"}",
"}"
] |
Abstract error object
@class ErrorAbstract
@access private
@param {string} [msg] Error message
@param {function} constructor
|
[
"Abstract",
"error",
"object"
] |
f418a0aea5a2db8806280e682b5084533b8410f1
|
https://github.com/GetStream/stream-js/blob/f418a0aea5a2db8806280e682b5084533b8410f1/src/lib/errors.js#L13-L26
|
9,925
|
higlass/higlass
|
app/scripts/PixiTrack.js
|
formatResolutionText
|
function formatResolutionText(resolution, maxResolutionSize) {
const pp = precisionPrefix(maxResolutionSize, resolution);
const f = formatPrefix(`.${pp}`, resolution);
const formattedResolution = f(resolution);
return formattedResolution;
}
|
javascript
|
function formatResolutionText(resolution, maxResolutionSize) {
const pp = precisionPrefix(maxResolutionSize, resolution);
const f = formatPrefix(`.${pp}`, resolution);
const formattedResolution = f(resolution);
return formattedResolution;
}
|
[
"function",
"formatResolutionText",
"(",
"resolution",
",",
"maxResolutionSize",
")",
"{",
"const",
"pp",
"=",
"precisionPrefix",
"(",
"maxResolutionSize",
",",
"resolution",
")",
";",
"const",
"f",
"=",
"formatPrefix",
"(",
"`",
"${",
"pp",
"}",
"`",
",",
"resolution",
")",
";",
"const",
"formattedResolution",
"=",
"f",
"(",
"resolution",
")",
";",
"return",
"formattedResolution",
";",
"}"
] |
Format a resolution relative to the highest possible resolution.
The highest possible resolution determines the granularity of the
formatting (e.g. 20K vs 20000)
@param {int} resolution The resolution to format (e.g. 30000)
@param {int} maxResolutionSize The maximum possible resolution (e.g. 1000)
@returns {string} A formatted resolution string (e.g. "30K")
|
[
"Format",
"a",
"resolution",
"relative",
"to",
"the",
"highest",
"possible",
"resolution",
"."
] |
a1df80c6c24b66a1e66710dbe562184a1b6d8de8
|
https://github.com/higlass/higlass/blob/a1df80c6c24b66a1e66710dbe562184a1b6d8de8/app/scripts/PixiTrack.js#L19-L25
|
9,926
|
higlass/higlass
|
app/scripts/PixiTrack.js
|
getResolutionBasedResolutionText
|
function getResolutionBasedResolutionText(resolutions, zoomLevel) {
const sortedResolutions = resolutions.map(x => +x).sort((a, b) => b - a);
const resolution = sortedResolutions[zoomLevel];
const maxResolutionSize = sortedResolutions[sortedResolutions.length - 1];
return formatResolutionText(resolution, maxResolutionSize);
}
|
javascript
|
function getResolutionBasedResolutionText(resolutions, zoomLevel) {
const sortedResolutions = resolutions.map(x => +x).sort((a, b) => b - a);
const resolution = sortedResolutions[zoomLevel];
const maxResolutionSize = sortedResolutions[sortedResolutions.length - 1];
return formatResolutionText(resolution, maxResolutionSize);
}
|
[
"function",
"getResolutionBasedResolutionText",
"(",
"resolutions",
",",
"zoomLevel",
")",
"{",
"const",
"sortedResolutions",
"=",
"resolutions",
".",
"map",
"(",
"x",
"=>",
"+",
"x",
")",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"b",
"-",
"a",
")",
";",
"const",
"resolution",
"=",
"sortedResolutions",
"[",
"zoomLevel",
"]",
";",
"const",
"maxResolutionSize",
"=",
"sortedResolutions",
"[",
"sortedResolutions",
".",
"length",
"-",
"1",
"]",
";",
"return",
"formatResolutionText",
"(",
"resolution",
",",
"maxResolutionSize",
")",
";",
"}"
] |
Get a text description of a resolution based on a zoom level
and a list of resolutions
@param {list} resolutions: A list of resolutions (e.g. [1000,2000,3000])
@param {int} zoomLevel: The current zoom level (e.g. 4)
@returns {string} A formatted string representation of the zoom level
(e.g. "30K")
|
[
"Get",
"a",
"text",
"description",
"of",
"a",
"resolution",
"based",
"on",
"a",
"zoom",
"level",
"and",
"a",
"list",
"of",
"resolutions"
] |
a1df80c6c24b66a1e66710dbe562184a1b6d8de8
|
https://github.com/higlass/higlass/blob/a1df80c6c24b66a1e66710dbe562184a1b6d8de8/app/scripts/PixiTrack.js#L37-L43
|
9,927
|
higlass/higlass
|
app/scripts/PixiTrack.js
|
getWidthBasedResolutionText
|
function getWidthBasedResolutionText(
zoomLevel, maxWidth, binsPerDimension, maxZoom
) {
const resolution = maxWidth / ((2 ** zoomLevel) * binsPerDimension);
// we can't display a NaN resolution
if (!Number.isNaN(resolution)) {
// what is the maximum possible resolution?
// this will determine how we format the lower resolutions
const maxResolutionSize = maxWidth / ((2 ** maxZoom) * binsPerDimension);
const pp = precisionPrefix(maxResolutionSize, resolution);
const f = formatPrefix(`.${pp}`, resolution);
const formattedResolution = f(resolution);
return formattedResolution;
}
console.warn(
'NaN resolution, screen is probably too small. Dimensions:',
this.dimensions,
);
return '';
}
|
javascript
|
function getWidthBasedResolutionText(
zoomLevel, maxWidth, binsPerDimension, maxZoom
) {
const resolution = maxWidth / ((2 ** zoomLevel) * binsPerDimension);
// we can't display a NaN resolution
if (!Number.isNaN(resolution)) {
// what is the maximum possible resolution?
// this will determine how we format the lower resolutions
const maxResolutionSize = maxWidth / ((2 ** maxZoom) * binsPerDimension);
const pp = precisionPrefix(maxResolutionSize, resolution);
const f = formatPrefix(`.${pp}`, resolution);
const formattedResolution = f(resolution);
return formattedResolution;
}
console.warn(
'NaN resolution, screen is probably too small. Dimensions:',
this.dimensions,
);
return '';
}
|
[
"function",
"getWidthBasedResolutionText",
"(",
"zoomLevel",
",",
"maxWidth",
",",
"binsPerDimension",
",",
"maxZoom",
")",
"{",
"const",
"resolution",
"=",
"maxWidth",
"/",
"(",
"(",
"2",
"**",
"zoomLevel",
")",
"*",
"binsPerDimension",
")",
";",
"// we can't display a NaN resolution",
"if",
"(",
"!",
"Number",
".",
"isNaN",
"(",
"resolution",
")",
")",
"{",
"// what is the maximum possible resolution?",
"// this will determine how we format the lower resolutions",
"const",
"maxResolutionSize",
"=",
"maxWidth",
"/",
"(",
"(",
"2",
"**",
"maxZoom",
")",
"*",
"binsPerDimension",
")",
";",
"const",
"pp",
"=",
"precisionPrefix",
"(",
"maxResolutionSize",
",",
"resolution",
")",
";",
"const",
"f",
"=",
"formatPrefix",
"(",
"`",
"${",
"pp",
"}",
"`",
",",
"resolution",
")",
";",
"const",
"formattedResolution",
"=",
"f",
"(",
"resolution",
")",
";",
"return",
"formattedResolution",
";",
"}",
"console",
".",
"warn",
"(",
"'NaN resolution, screen is probably too small. Dimensions:'",
",",
"this",
".",
"dimensions",
",",
")",
";",
"return",
"''",
";",
"}"
] |
Get a text description of the resolution based on the zoom level
max width of the dataset, the bins per dimension and the maximum
zoom.
@param {int} zoomLevel The current zoomLevel (e.g. 0)
@param {int} max_width The max width
(e.g. 2 ** maxZoom * highestResolution * binsPerDimension)
@param {int} bins_per_dimension The number of bins per tile dimension
(e.g. 256)
@param {int} maxZoom The maximum zoom level for this tileset
@returns {string} A formatted string representation of the zoom level
(e.g. "30K")
|
[
"Get",
"a",
"text",
"description",
"of",
"the",
"resolution",
"based",
"on",
"the",
"zoom",
"level",
"max",
"width",
"of",
"the",
"dataset",
"the",
"bins",
"per",
"dimension",
"and",
"the",
"maximum",
"zoom",
"."
] |
a1df80c6c24b66a1e66710dbe562184a1b6d8de8
|
https://github.com/higlass/higlass/blob/a1df80c6c24b66a1e66710dbe562184a1b6d8de8/app/scripts/PixiTrack.js#L60-L83
|
9,928
|
higlass/higlass
|
app/scripts/services/tile-proxy.js
|
json
|
async function json(url, callback, pubSub) {
// Fritz: What is going on here? Can someone explain?
if (url.indexOf('hg19') >= 0) {
await sleep(1);
}
// console.log('url:', url);
return fetchEither(url, callback, 'json', pubSub);
}
|
javascript
|
async function json(url, callback, pubSub) {
// Fritz: What is going on here? Can someone explain?
if (url.indexOf('hg19') >= 0) {
await sleep(1);
}
// console.log('url:', url);
return fetchEither(url, callback, 'json', pubSub);
}
|
[
"async",
"function",
"json",
"(",
"url",
",",
"callback",
",",
"pubSub",
")",
"{",
"// Fritz: What is going on here? Can someone explain?",
"if",
"(",
"url",
".",
"indexOf",
"(",
"'hg19'",
")",
">=",
"0",
")",
"{",
"await",
"sleep",
"(",
"1",
")",
";",
"}",
"// console.log('url:', url);",
"return",
"fetchEither",
"(",
"url",
",",
"callback",
",",
"'json'",
",",
"pubSub",
")",
";",
"}"
] |
Send a JSON request and mark it so that we can tell how many are in flight
@param url: URL to fetch
@param callback: Callback to execute with content from fetch
|
[
"Send",
"a",
"JSON",
"request",
"and",
"mark",
"it",
"so",
"that",
"we",
"can",
"tell",
"how",
"many",
"are",
"in",
"flight"
] |
a1df80c6c24b66a1e66710dbe562184a1b6d8de8
|
https://github.com/higlass/higlass/blob/a1df80c6c24b66a1e66710dbe562184a1b6d8de8/app/scripts/services/tile-proxy.js#L606-L613
|
9,929
|
postmanlabs/postman-runtime
|
lib/authorizer/oauth1.js
|
function (params) {
var url = params.url,
method = params.method,
helperParams = params.helperParams,
queryParams = params.queryParams,
bodyParams = params.bodyParams,
signatureParams,
message,
accessor = {},
allParams,
signature;
signatureParams = [
{system: true, key: OAUTH1_PARAMS.oauthConsumerKey, value: helperParams.consumerKey},
{system: true, key: OAUTH1_PARAMS.oauthToken, value: helperParams.token},
{system: true, key: OAUTH1_PARAMS.oauthSignatureMethod, value: helperParams.signatureMethod},
{system: true, key: OAUTH1_PARAMS.oauthTimestamp, value: helperParams.timestamp},
{system: true, key: OAUTH1_PARAMS.oauthNonce, value: helperParams.nonce},
{system: true, key: OAUTH1_PARAMS.oauthVersion, value: helperParams.version}
];
signatureParams = _.filter(signatureParams, function (param) {
return helperParams.addEmptyParamsToSign || param.value;
});
allParams = [].concat(signatureParams, queryParams, bodyParams);
message = {
action: url,
method: method,
parameters: _.map(allParams, function (param) {
return [param.key, param.value];
})
};
if (helperParams.consumerSecret) {
accessor.consumerSecret = helperParams.consumerSecret;
}
if (helperParams.tokenSecret) {
accessor.tokenSecret = helperParams.tokenSecret;
}
signature = oAuth1.SignatureMethod.sign(message, accessor);
signatureParams.push({system: true, key: OAUTH1_PARAMS.oauthSignature, value: signature});
return signatureParams;
}
|
javascript
|
function (params) {
var url = params.url,
method = params.method,
helperParams = params.helperParams,
queryParams = params.queryParams,
bodyParams = params.bodyParams,
signatureParams,
message,
accessor = {},
allParams,
signature;
signatureParams = [
{system: true, key: OAUTH1_PARAMS.oauthConsumerKey, value: helperParams.consumerKey},
{system: true, key: OAUTH1_PARAMS.oauthToken, value: helperParams.token},
{system: true, key: OAUTH1_PARAMS.oauthSignatureMethod, value: helperParams.signatureMethod},
{system: true, key: OAUTH1_PARAMS.oauthTimestamp, value: helperParams.timestamp},
{system: true, key: OAUTH1_PARAMS.oauthNonce, value: helperParams.nonce},
{system: true, key: OAUTH1_PARAMS.oauthVersion, value: helperParams.version}
];
signatureParams = _.filter(signatureParams, function (param) {
return helperParams.addEmptyParamsToSign || param.value;
});
allParams = [].concat(signatureParams, queryParams, bodyParams);
message = {
action: url,
method: method,
parameters: _.map(allParams, function (param) {
return [param.key, param.value];
})
};
if (helperParams.consumerSecret) {
accessor.consumerSecret = helperParams.consumerSecret;
}
if (helperParams.tokenSecret) {
accessor.tokenSecret = helperParams.tokenSecret;
}
signature = oAuth1.SignatureMethod.sign(message, accessor);
signatureParams.push({system: true, key: OAUTH1_PARAMS.oauthSignature, value: signature});
return signatureParams;
}
|
[
"function",
"(",
"params",
")",
"{",
"var",
"url",
"=",
"params",
".",
"url",
",",
"method",
"=",
"params",
".",
"method",
",",
"helperParams",
"=",
"params",
".",
"helperParams",
",",
"queryParams",
"=",
"params",
".",
"queryParams",
",",
"bodyParams",
"=",
"params",
".",
"bodyParams",
",",
"signatureParams",
",",
"message",
",",
"accessor",
"=",
"{",
"}",
",",
"allParams",
",",
"signature",
";",
"signatureParams",
"=",
"[",
"{",
"system",
":",
"true",
",",
"key",
":",
"OAUTH1_PARAMS",
".",
"oauthConsumerKey",
",",
"value",
":",
"helperParams",
".",
"consumerKey",
"}",
",",
"{",
"system",
":",
"true",
",",
"key",
":",
"OAUTH1_PARAMS",
".",
"oauthToken",
",",
"value",
":",
"helperParams",
".",
"token",
"}",
",",
"{",
"system",
":",
"true",
",",
"key",
":",
"OAUTH1_PARAMS",
".",
"oauthSignatureMethod",
",",
"value",
":",
"helperParams",
".",
"signatureMethod",
"}",
",",
"{",
"system",
":",
"true",
",",
"key",
":",
"OAUTH1_PARAMS",
".",
"oauthTimestamp",
",",
"value",
":",
"helperParams",
".",
"timestamp",
"}",
",",
"{",
"system",
":",
"true",
",",
"key",
":",
"OAUTH1_PARAMS",
".",
"oauthNonce",
",",
"value",
":",
"helperParams",
".",
"nonce",
"}",
",",
"{",
"system",
":",
"true",
",",
"key",
":",
"OAUTH1_PARAMS",
".",
"oauthVersion",
",",
"value",
":",
"helperParams",
".",
"version",
"}",
"]",
";",
"signatureParams",
"=",
"_",
".",
"filter",
"(",
"signatureParams",
",",
"function",
"(",
"param",
")",
"{",
"return",
"helperParams",
".",
"addEmptyParamsToSign",
"||",
"param",
".",
"value",
";",
"}",
")",
";",
"allParams",
"=",
"[",
"]",
".",
"concat",
"(",
"signatureParams",
",",
"queryParams",
",",
"bodyParams",
")",
";",
"message",
"=",
"{",
"action",
":",
"url",
",",
"method",
":",
"method",
",",
"parameters",
":",
"_",
".",
"map",
"(",
"allParams",
",",
"function",
"(",
"param",
")",
"{",
"return",
"[",
"param",
".",
"key",
",",
"param",
".",
"value",
"]",
";",
"}",
")",
"}",
";",
"if",
"(",
"helperParams",
".",
"consumerSecret",
")",
"{",
"accessor",
".",
"consumerSecret",
"=",
"helperParams",
".",
"consumerSecret",
";",
"}",
"if",
"(",
"helperParams",
".",
"tokenSecret",
")",
"{",
"accessor",
".",
"tokenSecret",
"=",
"helperParams",
".",
"tokenSecret",
";",
"}",
"signature",
"=",
"oAuth1",
".",
"SignatureMethod",
".",
"sign",
"(",
"message",
",",
"accessor",
")",
";",
"signatureParams",
".",
"push",
"(",
"{",
"system",
":",
"true",
",",
"key",
":",
"OAUTH1_PARAMS",
".",
"oauthSignature",
",",
"value",
":",
"signature",
"}",
")",
";",
"return",
"signatureParams",
";",
"}"
] |
Generates a oAuth1.
@param {Object} params
@param {String} params.url OAuth 1.0 Base URL
@param {String} params.method Request method
@param {Object[]} params.helperParams The auth parameters stored with the `Request`
@param {Object[]} params.queryParams An array of query parameters
@param {Object[]} params.bodyParams An array of request body parameters (in case of url-encoded bodies)
@returns {*}
|
[
"Generates",
"a",
"oAuth1",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/authorizer/oauth1.js#L170-L214
|
|
9,930
|
postmanlabs/postman-runtime
|
lib/requester/core.js
|
function (headers, headerKey, defaultValue) {
var headerName = _.findKey(headers, function (value, key) {
return key.toLowerCase() === headerKey.toLowerCase();
});
if (!headerName) {
headers[headerKey] = defaultValue;
}
}
|
javascript
|
function (headers, headerKey, defaultValue) {
var headerName = _.findKey(headers, function (value, key) {
return key.toLowerCase() === headerKey.toLowerCase();
});
if (!headerName) {
headers[headerKey] = defaultValue;
}
}
|
[
"function",
"(",
"headers",
",",
"headerKey",
",",
"defaultValue",
")",
"{",
"var",
"headerName",
"=",
"_",
".",
"findKey",
"(",
"headers",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"return",
"key",
".",
"toLowerCase",
"(",
")",
"===",
"headerKey",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"headerName",
")",
"{",
"headers",
"[",
"headerKey",
"]",
"=",
"defaultValue",
";",
"}",
"}"
] |
Checks if a header already exists. If it does not, sets the value to whatever is passed as
`defaultValue`
@param {object} headers
@param {String} headerKey
@param {String} defaultValue
|
[
"Checks",
"if",
"a",
"header",
"already",
"exists",
".",
"If",
"it",
"does",
"not",
"sets",
"the",
"value",
"to",
"whatever",
"is",
"passed",
"as",
"defaultValue"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/requester/core.js#L331-L339
|
|
9,931
|
postmanlabs/postman-runtime
|
lib/requester/core.js
|
function (request, protocolProfileBehavior) {
if (!(request && request.body)) {
return;
}
var requestBody = request.body,
requestBodyType = requestBody.mode,
requestMethod = (typeof request.method === 'string') ? request.method.toLowerCase() : undefined,
bodyIsEmpty = requestBody.isEmpty(),
bodyIsDisabled = requestBody.disabled,
bodyContent = requestBody[requestBodyType],
// flag to decide body pruning for METHODS_WITHOUT_BODY
// @note this will be `true` even if protocolProfileBehavior is undefined
pruneBody = protocolProfileBehavior ? !protocolProfileBehavior.disableBodyPruning : true;
// early bailout for empty or disabled body (this area has some legacy shenanigans)
if (bodyIsEmpty || bodyIsDisabled) {
return;
}
// bail out if request method doesn't support body and pruneBody is true.
if (METHODS_WITHOUT_BODY[requestMethod] && pruneBody) {
return;
}
// even if body is not empty, but the body type is not known, we do not know how to parse the same
//
// @note if you'd like to support additional body types beyond formdata, url-encoding, etc, add the same to
// the builder module
if (!requestBodyBuilders.hasOwnProperty(requestBodyType)) {
return;
}
return requestBodyBuilders[requestBodyType](bodyContent, request);
}
|
javascript
|
function (request, protocolProfileBehavior) {
if (!(request && request.body)) {
return;
}
var requestBody = request.body,
requestBodyType = requestBody.mode,
requestMethod = (typeof request.method === 'string') ? request.method.toLowerCase() : undefined,
bodyIsEmpty = requestBody.isEmpty(),
bodyIsDisabled = requestBody.disabled,
bodyContent = requestBody[requestBodyType],
// flag to decide body pruning for METHODS_WITHOUT_BODY
// @note this will be `true` even if protocolProfileBehavior is undefined
pruneBody = protocolProfileBehavior ? !protocolProfileBehavior.disableBodyPruning : true;
// early bailout for empty or disabled body (this area has some legacy shenanigans)
if (bodyIsEmpty || bodyIsDisabled) {
return;
}
// bail out if request method doesn't support body and pruneBody is true.
if (METHODS_WITHOUT_BODY[requestMethod] && pruneBody) {
return;
}
// even if body is not empty, but the body type is not known, we do not know how to parse the same
//
// @note if you'd like to support additional body types beyond formdata, url-encoding, etc, add the same to
// the builder module
if (!requestBodyBuilders.hasOwnProperty(requestBodyType)) {
return;
}
return requestBodyBuilders[requestBodyType](bodyContent, request);
}
|
[
"function",
"(",
"request",
",",
"protocolProfileBehavior",
")",
"{",
"if",
"(",
"!",
"(",
"request",
"&&",
"request",
".",
"body",
")",
")",
"{",
"return",
";",
"}",
"var",
"requestBody",
"=",
"request",
".",
"body",
",",
"requestBodyType",
"=",
"requestBody",
".",
"mode",
",",
"requestMethod",
"=",
"(",
"typeof",
"request",
".",
"method",
"===",
"'string'",
")",
"?",
"request",
".",
"method",
".",
"toLowerCase",
"(",
")",
":",
"undefined",
",",
"bodyIsEmpty",
"=",
"requestBody",
".",
"isEmpty",
"(",
")",
",",
"bodyIsDisabled",
"=",
"requestBody",
".",
"disabled",
",",
"bodyContent",
"=",
"requestBody",
"[",
"requestBodyType",
"]",
",",
"// flag to decide body pruning for METHODS_WITHOUT_BODY",
"// @note this will be `true` even if protocolProfileBehavior is undefined",
"pruneBody",
"=",
"protocolProfileBehavior",
"?",
"!",
"protocolProfileBehavior",
".",
"disableBodyPruning",
":",
"true",
";",
"// early bailout for empty or disabled body (this area has some legacy shenanigans)",
"if",
"(",
"bodyIsEmpty",
"||",
"bodyIsDisabled",
")",
"{",
"return",
";",
"}",
"// bail out if request method doesn't support body and pruneBody is true.",
"if",
"(",
"METHODS_WITHOUT_BODY",
"[",
"requestMethod",
"]",
"&&",
"pruneBody",
")",
"{",
"return",
";",
"}",
"// even if body is not empty, but the body type is not known, we do not know how to parse the same",
"//",
"// @note if you'd like to support additional body types beyond formdata, url-encoding, etc, add the same to",
"// the builder module",
"if",
"(",
"!",
"requestBodyBuilders",
".",
"hasOwnProperty",
"(",
"requestBodyType",
")",
")",
"{",
"return",
";",
"}",
"return",
"requestBodyBuilders",
"[",
"requestBodyType",
"]",
"(",
"bodyContent",
",",
"request",
")",
";",
"}"
] |
Processes a request body and puts it in a format compatible with
the "request" library.
@todo: Move this to the SDK.
@param request - Request object
@param protocolProfileBehavior - Protocol profile behaviors
@returns {Object}
|
[
"Processes",
"a",
"request",
"body",
"and",
"puts",
"it",
"in",
"a",
"format",
"compatible",
"with",
"the",
"request",
"library",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/requester/core.js#L351-L386
|
|
9,932
|
postmanlabs/postman-runtime
|
lib/requester/core.js
|
function (buffer) {
var str = '',
uArrayVal = new Uint8Array(buffer),
i,
ii;
for (i = 0, ii = uArrayVal.length; i < ii; i++) {
str += String.fromCharCode(uArrayVal[i]);
}
return str;
}
|
javascript
|
function (buffer) {
var str = '',
uArrayVal = new Uint8Array(buffer),
i,
ii;
for (i = 0, ii = uArrayVal.length; i < ii; i++) {
str += String.fromCharCode(uArrayVal[i]);
}
return str;
}
|
[
"function",
"(",
"buffer",
")",
"{",
"var",
"str",
"=",
"''",
",",
"uArrayVal",
"=",
"new",
"Uint8Array",
"(",
"buffer",
")",
",",
"i",
",",
"ii",
";",
"for",
"(",
"i",
"=",
"0",
",",
"ii",
"=",
"uArrayVal",
".",
"length",
";",
"i",
"<",
"ii",
";",
"i",
"++",
")",
"{",
"str",
"+=",
"String",
".",
"fromCharCode",
"(",
"uArrayVal",
"[",
"i",
"]",
")",
";",
"}",
"return",
"str",
";",
"}"
] |
ArrayBuffer to String
@param {ArrayBuffer} buffer
@returns {String}
|
[
"ArrayBuffer",
"to",
"String"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/requester/core.js#L446-L458
|
|
9,933
|
postmanlabs/postman-runtime
|
lib/requester/core.js
|
function (arr) {
if (!_.isArray(arr)) {
return;
}
var obj = {},
key,
val,
i,
ii;
for (i = 0, ii = arr.length; i < ii; i += 2) {
key = arr[i];
val = arr[i + 1];
if (_.has(obj, key)) {
!_.isArray(obj[key]) && (obj[key] = [obj[key]]);
obj[key].push(val);
}
else {
obj[key] = val;
}
}
return obj;
}
|
javascript
|
function (arr) {
if (!_.isArray(arr)) {
return;
}
var obj = {},
key,
val,
i,
ii;
for (i = 0, ii = arr.length; i < ii; i += 2) {
key = arr[i];
val = arr[i + 1];
if (_.has(obj, key)) {
!_.isArray(obj[key]) && (obj[key] = [obj[key]]);
obj[key].push(val);
}
else {
obj[key] = val;
}
}
return obj;
}
|
[
"function",
"(",
"arr",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"arr",
")",
")",
"{",
"return",
";",
"}",
"var",
"obj",
"=",
"{",
"}",
",",
"key",
",",
"val",
",",
"i",
",",
"ii",
";",
"for",
"(",
"i",
"=",
"0",
",",
"ii",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"ii",
";",
"i",
"+=",
"2",
")",
"{",
"key",
"=",
"arr",
"[",
"i",
"]",
";",
"val",
"=",
"arr",
"[",
"i",
"+",
"1",
"]",
";",
"if",
"(",
"_",
".",
"has",
"(",
"obj",
",",
"key",
")",
")",
"{",
"!",
"_",
".",
"isArray",
"(",
"obj",
"[",
"key",
"]",
")",
"&&",
"(",
"obj",
"[",
"key",
"]",
"=",
"[",
"obj",
"[",
"key",
"]",
"]",
")",
";",
"obj",
"[",
"key",
"]",
".",
"push",
"(",
"val",
")",
";",
"}",
"else",
"{",
"obj",
"[",
"key",
"]",
"=",
"val",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] |
Converts an array of sequential pairs to an object.
@param arr
@returns {{}}
@example
['a', 'b', 'c', 'd'] ====> {a: 'b', c: 'd' }
|
[
"Converts",
"an",
"array",
"of",
"sequential",
"pairs",
"to",
"an",
"object",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/requester/core.js#L469-L494
|
|
9,934
|
postmanlabs/postman-runtime
|
lib/authorizer/index.js
|
function (Handler, name) {
if (!_.isFunction(Handler.init)) {
throw new Error('The handler for "' + name + '" does not have an "init" function, which is necessary');
}
if (!_.isFunction(Handler.pre)) {
throw new Error('The handler for "' + name + '" does not have a "pre" function, which is necessary');
}
if (!_.isFunction(Handler.post)) {
throw new Error('The handler for "' + name + '" does not have a "post" function, which is necessary');
}
if (!_.isFunction(Handler.sign)) {
throw new Error('The handler for "' + name + '" does not have a "sign" function, which is necessary');
}
Object.defineProperty(Handler, AUTH_TYPE_PROP, {
value: name,
configurable: false,
enumerable: false,
writable: false
});
AuthLoader.handlers[name] = Handler;
}
|
javascript
|
function (Handler, name) {
if (!_.isFunction(Handler.init)) {
throw new Error('The handler for "' + name + '" does not have an "init" function, which is necessary');
}
if (!_.isFunction(Handler.pre)) {
throw new Error('The handler for "' + name + '" does not have a "pre" function, which is necessary');
}
if (!_.isFunction(Handler.post)) {
throw new Error('The handler for "' + name + '" does not have a "post" function, which is necessary');
}
if (!_.isFunction(Handler.sign)) {
throw new Error('The handler for "' + name + '" does not have a "sign" function, which is necessary');
}
Object.defineProperty(Handler, AUTH_TYPE_PROP, {
value: name,
configurable: false,
enumerable: false,
writable: false
});
AuthLoader.handlers[name] = Handler;
}
|
[
"function",
"(",
"Handler",
",",
"name",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"Handler",
".",
"init",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The handler for \"'",
"+",
"name",
"+",
"'\" does not have an \"init\" function, which is necessary'",
")",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"Handler",
".",
"pre",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The handler for \"'",
"+",
"name",
"+",
"'\" does not have a \"pre\" function, which is necessary'",
")",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"Handler",
".",
"post",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The handler for \"'",
"+",
"name",
"+",
"'\" does not have a \"post\" function, which is necessary'",
")",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"Handler",
".",
"sign",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The handler for \"'",
"+",
"name",
"+",
"'\" does not have a \"sign\" function, which is necessary'",
")",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"Handler",
",",
"AUTH_TYPE_PROP",
",",
"{",
"value",
":",
"name",
",",
"configurable",
":",
"false",
",",
"enumerable",
":",
"false",
",",
"writable",
":",
"false",
"}",
")",
";",
"AuthLoader",
".",
"handlers",
"[",
"name",
"]",
"=",
"Handler",
";",
"}"
] |
Adds a Handler for use with given Auth type.
@param Handler
@param name
|
[
"Adds",
"a",
"Handler",
"for",
"use",
"with",
"given",
"Auth",
"type",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/authorizer/index.js#L41-L66
|
|
9,935
|
postmanlabs/postman-runtime
|
lib/runner/request-helpers-postsend.js
|
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
var auth = context.auth,
originalAuth = context.originalItem.getAuth(),
originalAuthParams = originalAuth && originalAuth.parameters(),
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// bail out if there is no matching auth handler for the type
if (!authHandler) {
run.triggers.console(context.coords, 'warn', 'runtime: could not find a handler for auth: ' + auth.type);
return done();
}
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync all auth system parameters to the original auth
originalAuthParams && auth.parameters().each(function (param) {
param && param.system && originalAuthParams.upsert({key: param.key, value: param.value, system: true});
});
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
// warn the user but don't bubble it up
if (err) {
run.triggers.console(
context.coords,
'warn',
'runtime~' + auth.type + '.auth: there was an error validating auth: ' + (err.message || err),
err
);
return done();
}
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true, helper: auth.type + DOT_AUTH});
});
}
|
javascript
|
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
var auth = context.auth,
originalAuth = context.originalItem.getAuth(),
originalAuthParams = originalAuth && originalAuth.parameters(),
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// bail out if there is no matching auth handler for the type
if (!authHandler) {
run.triggers.console(context.coords, 'warn', 'runtime: could not find a handler for auth: ' + auth.type);
return done();
}
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync all auth system parameters to the original auth
originalAuthParams && auth.parameters().each(function (param) {
param && param.system && originalAuthParams.upsert({key: param.key, value: param.value, system: true});
});
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
// warn the user but don't bubble it up
if (err) {
run.triggers.console(
context.coords,
'warn',
'runtime~' + auth.type + '.auth: there was an error validating auth: ' + (err.message || err),
err
);
return done();
}
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true, helper: auth.type + DOT_AUTH});
});
}
|
[
"function",
"(",
"context",
",",
"run",
",",
"done",
")",
"{",
"// if no response is provided, there's nothing to do, and probably means that the request errored out",
"// let the actual request command handle whatever needs to be done.",
"if",
"(",
"!",
"context",
".",
"response",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"// bail out if there is no auth",
"if",
"(",
"!",
"(",
"context",
".",
"auth",
"&&",
"context",
".",
"auth",
".",
"type",
")",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"var",
"auth",
"=",
"context",
".",
"auth",
",",
"originalAuth",
"=",
"context",
".",
"originalItem",
".",
"getAuth",
"(",
")",
",",
"originalAuthParams",
"=",
"originalAuth",
"&&",
"originalAuth",
".",
"parameters",
"(",
")",
",",
"authHandler",
"=",
"AuthLoader",
".",
"getHandler",
"(",
"auth",
".",
"type",
")",
",",
"authInterface",
"=",
"createAuthInterface",
"(",
"auth",
")",
";",
"// bail out if there is no matching auth handler for the type",
"if",
"(",
"!",
"authHandler",
")",
"{",
"run",
".",
"triggers",
".",
"console",
"(",
"context",
".",
"coords",
",",
"'warn'",
",",
"'runtime: could not find a handler for auth: '",
"+",
"auth",
".",
"type",
")",
";",
"return",
"done",
"(",
")",
";",
"}",
"// invoke `post` on the Auth",
"authHandler",
".",
"post",
"(",
"authInterface",
",",
"context",
".",
"response",
",",
"function",
"(",
"err",
",",
"success",
")",
"{",
"// sync all auth system parameters to the original auth",
"originalAuthParams",
"&&",
"auth",
".",
"parameters",
"(",
")",
".",
"each",
"(",
"function",
"(",
"param",
")",
"{",
"param",
"&&",
"param",
".",
"system",
"&&",
"originalAuthParams",
".",
"upsert",
"(",
"{",
"key",
":",
"param",
".",
"key",
",",
"value",
":",
"param",
".",
"value",
",",
"system",
":",
"true",
"}",
")",
";",
"}",
")",
";",
"// sync auth state back to item request",
"_",
".",
"set",
"(",
"context",
",",
"'item.request.auth'",
",",
"auth",
")",
";",
"// there was an error in auth post hook",
"// warn the user but don't bubble it up",
"if",
"(",
"err",
")",
"{",
"run",
".",
"triggers",
".",
"console",
"(",
"context",
".",
"coords",
",",
"'warn'",
",",
"'runtime~'",
"+",
"auth",
".",
"type",
"+",
"'.auth: there was an error validating auth: '",
"+",
"(",
"err",
".",
"message",
"||",
"err",
")",
",",
"err",
")",
";",
"return",
"done",
"(",
")",
";",
"}",
"// auth was verified",
"if",
"(",
"success",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"// request a replay of request",
"done",
"(",
"null",
",",
"{",
"replay",
":",
"true",
",",
"helper",
":",
"auth",
".",
"type",
"+",
"DOT_AUTH",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Post authorization.
|
[
"Post",
"authorization",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/request-helpers-postsend.js#L10-L60
|
|
9,936
|
postmanlabs/postman-runtime
|
lib/authorizer/hawk.js
|
function (auth, done) {
!auth.get('nonce') && auth.set('nonce', randomString(6));
!_.parseInt(auth.get('timestamp')) && auth.set('timestamp', Math.floor(Date.now() / 1e3));
done(null, true);
}
|
javascript
|
function (auth, done) {
!auth.get('nonce') && auth.set('nonce', randomString(6));
!_.parseInt(auth.get('timestamp')) && auth.set('timestamp', Math.floor(Date.now() / 1e3));
done(null, true);
}
|
[
"function",
"(",
"auth",
",",
"done",
")",
"{",
"!",
"auth",
".",
"get",
"(",
"'nonce'",
")",
"&&",
"auth",
".",
"set",
"(",
"'nonce'",
",",
"randomString",
"(",
"6",
")",
")",
";",
"!",
"_",
".",
"parseInt",
"(",
"auth",
".",
"get",
"(",
"'timestamp'",
")",
")",
"&&",
"auth",
".",
"set",
"(",
"'timestamp'",
",",
"Math",
".",
"floor",
"(",
"Date",
".",
"now",
"(",
")",
"/",
"1e3",
")",
")",
";",
"done",
"(",
"null",
",",
"true",
")",
";",
"}"
] |
Checks the item, and fetches any parameters that are not already provided.
Sanitizes the auth parameters if needed.
@param {AuthInterface} auth
@param {AuthHandlerInterface~authPreHookCallback} done
|
[
"Checks",
"the",
"item",
"and",
"fetches",
"any",
"parameters",
"that",
"are",
"not",
"already",
"provided",
".",
"Sanitizes",
"the",
"auth",
"parameters",
"if",
"needed",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/authorizer/hawk.js#L159-L163
|
|
9,937
|
postmanlabs/postman-runtime
|
lib/authorizer/hawk.js
|
function (params) {
return Hawk.header(url.parse(params.url), params.method, params);
}
|
javascript
|
function (params) {
return Hawk.header(url.parse(params.url), params.method, params);
}
|
[
"function",
"(",
"params",
")",
"{",
"return",
"Hawk",
".",
"header",
"(",
"url",
".",
"parse",
"(",
"params",
".",
"url",
")",
",",
"params",
".",
"method",
",",
"params",
")",
";",
"}"
] |
Computes signature and Auth header for a request.
@param {Object} params
@param {Object} params.credentials Contains hawk auth credentials, "id", "key" and "algorithm"
@param {String} params.nonce
@param {String} params.ext Extra data that may be associated with the request.
@param {String} params.app Application ID used in Oz authorization protocol
@param {String} params.dlg Delegation information (used in the Oz protocol)
@param {String} params.user User id
@param {String} params.url Complete request URL
@param {String} params.method Request method
@returns {*}
|
[
"Computes",
"signature",
"and",
"Auth",
"header",
"for",
"a",
"request",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/authorizer/hawk.js#L191-L193
|
|
9,938
|
postmanlabs/postman-runtime
|
lib/runner/replay-controller.js
|
function (context, item, desiredPayload, success, failure) {
// max retries exceeded
if (this.count >= MAX_REPLAY_COUNT) {
return failure(new Error('runtime: maximum intermediate request limit exceeded'));
}
// update replay count state
this.count++;
// update replay state to context
context.replayState = this.getReplayState();
// construct payload for request
var payload = _.defaults({
item: item,
// abortOnError makes sure request command bubbles errors
// so we can pass it on to the callback
abortOnError: true
}, desiredPayload);
// create item context from the new item
payload.context = createItemContext(payload, context);
this.run.immediate('httprequest', payload)
.done(function (response) {
success(null, response);
})
.catch(success);
}
|
javascript
|
function (context, item, desiredPayload, success, failure) {
// max retries exceeded
if (this.count >= MAX_REPLAY_COUNT) {
return failure(new Error('runtime: maximum intermediate request limit exceeded'));
}
// update replay count state
this.count++;
// update replay state to context
context.replayState = this.getReplayState();
// construct payload for request
var payload = _.defaults({
item: item,
// abortOnError makes sure request command bubbles errors
// so we can pass it on to the callback
abortOnError: true
}, desiredPayload);
// create item context from the new item
payload.context = createItemContext(payload, context);
this.run.immediate('httprequest', payload)
.done(function (response) {
success(null, response);
})
.catch(success);
}
|
[
"function",
"(",
"context",
",",
"item",
",",
"desiredPayload",
",",
"success",
",",
"failure",
")",
"{",
"// max retries exceeded",
"if",
"(",
"this",
".",
"count",
">=",
"MAX_REPLAY_COUNT",
")",
"{",
"return",
"failure",
"(",
"new",
"Error",
"(",
"'runtime: maximum intermediate request limit exceeded'",
")",
")",
";",
"}",
"// update replay count state",
"this",
".",
"count",
"++",
";",
"// update replay state to context",
"context",
".",
"replayState",
"=",
"this",
".",
"getReplayState",
"(",
")",
";",
"// construct payload for request",
"var",
"payload",
"=",
"_",
".",
"defaults",
"(",
"{",
"item",
":",
"item",
",",
"// abortOnError makes sure request command bubbles errors",
"// so we can pass it on to the callback",
"abortOnError",
":",
"true",
"}",
",",
"desiredPayload",
")",
";",
"// create item context from the new item",
"payload",
".",
"context",
"=",
"createItemContext",
"(",
"payload",
",",
"context",
")",
";",
"this",
".",
"run",
".",
"immediate",
"(",
"'httprequest'",
",",
"payload",
")",
".",
"done",
"(",
"function",
"(",
"response",
")",
"{",
"success",
"(",
"null",
",",
"response",
")",
";",
"}",
")",
".",
"catch",
"(",
"success",
")",
";",
"}"
] |
Sends a request in the item. This takes care of limiting the total number of replays for a request.
@param {Object} context
@param {Request} item
@param {Object} desiredPayload a partial payload to use for the replay request
@param {Function} success this callback is invoked when replay controller sent the request
@param {Function} failure this callback is invoked when replay controller decided not to send the request
|
[
"Sends",
"a",
"request",
"in",
"the",
"item",
".",
"This",
"takes",
"care",
"of",
"limiting",
"the",
"total",
"number",
"of",
"replays",
"for",
"a",
"request",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/replay-controller.js#L34-L62
|
|
9,939
|
postmanlabs/postman-runtime
|
lib/runner/request-helpers-presend.js
|
function () {
try {
authHandler.sign(authInterface, context.item.request, function (err) {
// handle all types of errors in one place, see catch block
if (err) { throw err; }
done();
});
}
catch (err) {
// handles synchronous and asynchronous errors in auth.sign
run.triggers.console(context.coords,
'warn',
'runtime~' + authType + '.auth: could not sign the request: ' + (err.message || err),
err
);
// swallow the error, we've warned the user
done();
}
}
|
javascript
|
function () {
try {
authHandler.sign(authInterface, context.item.request, function (err) {
// handle all types of errors in one place, see catch block
if (err) { throw err; }
done();
});
}
catch (err) {
// handles synchronous and asynchronous errors in auth.sign
run.triggers.console(context.coords,
'warn',
'runtime~' + authType + '.auth: could not sign the request: ' + (err.message || err),
err
);
// swallow the error, we've warned the user
done();
}
}
|
[
"function",
"(",
")",
"{",
"try",
"{",
"authHandler",
".",
"sign",
"(",
"authInterface",
",",
"context",
".",
"item",
".",
"request",
",",
"function",
"(",
"err",
")",
"{",
"// handle all types of errors in one place, see catch block",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"done",
"(",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"// handles synchronous and asynchronous errors in auth.sign",
"run",
".",
"triggers",
".",
"console",
"(",
"context",
".",
"coords",
",",
"'warn'",
",",
"'runtime~'",
"+",
"authType",
"+",
"'.auth: could not sign the request: '",
"+",
"(",
"err",
".",
"message",
"||",
"err",
")",
",",
"err",
")",
";",
"// swallow the error, we've warned the user",
"done",
"(",
")",
";",
"}",
"}"
] |
get auth handler
|
[
"get",
"auth",
"handler"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/request-helpers-presend.js#L164-L184
|
|
9,940
|
postmanlabs/postman-runtime
|
lib/runner/request-helpers-presend.js
|
function (cb) {
if (_.isFunction(_.get(proxies, 'resolve'))) {
return cb(null, proxies.resolve(url));
}
return cb(null, undefined);
}
|
javascript
|
function (cb) {
if (_.isFunction(_.get(proxies, 'resolve'))) {
return cb(null, proxies.resolve(url));
}
return cb(null, undefined);
}
|
[
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"_",
".",
"get",
"(",
"proxies",
",",
"'resolve'",
")",
")",
")",
"{",
"return",
"cb",
"(",
"null",
",",
"proxies",
".",
"resolve",
"(",
"url",
")",
")",
";",
"}",
"return",
"cb",
"(",
"null",
",",
"undefined",
")",
";",
"}"
] |
try resolving custom proxies before falling-back to system proxy
|
[
"try",
"resolving",
"custom",
"proxies",
"before",
"falling",
"-",
"back",
"to",
"system",
"proxy"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/request-helpers-presend.js#L293-L299
|
|
9,941
|
postmanlabs/postman-runtime
|
lib/runner/request-helpers-presend.js
|
function (config, cb) {
if (config) {
return cb(null, config);
}
return _.isFunction(run.options.systemProxy) ? run.options.systemProxy(url, cb) : cb(null, undefined);
}
|
javascript
|
function (config, cb) {
if (config) {
return cb(null, config);
}
return _.isFunction(run.options.systemProxy) ? run.options.systemProxy(url, cb) : cb(null, undefined);
}
|
[
"function",
"(",
"config",
",",
"cb",
")",
"{",
"if",
"(",
"config",
")",
"{",
"return",
"cb",
"(",
"null",
",",
"config",
")",
";",
"}",
"return",
"_",
".",
"isFunction",
"(",
"run",
".",
"options",
".",
"systemProxy",
")",
"?",
"run",
".",
"options",
".",
"systemProxy",
"(",
"url",
",",
"cb",
")",
":",
"cb",
"(",
"null",
",",
"undefined",
")",
";",
"}"
] |
fallback to system proxy
|
[
"fallback",
"to",
"system",
"proxy"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/request-helpers-presend.js#L301-L307
|
|
9,942
|
postmanlabs/postman-runtime
|
lib/runner/request-helpers-presend.js
|
function (context, run, done) {
var request,
pfxPath,
keyPath,
certPath,
fileResolver,
certificate;
// A. Check if we have the file resolver
fileResolver = run.options.fileResolver;
if (!fileResolver) { return done(); } // No point going ahead
// B. Ensure we have the request
request = _.get(context.item, 'request');
if (!request) { return done(new Error('No request to resolve certificates for.')); }
// C. See if any cert should be sent, by performing a URL matching
certificate = run.options.certificates && run.options.certificates.resolveOne(request.url);
if (!certificate) { return done(); }
// D. Fetch the paths
// @todo: check why aren't we reading ca file (why are we not supporting ca file)
pfxPath = _.get(certificate, 'pfx.src');
keyPath = _.get(certificate, 'key.src');
certPath = _.get(certificate, 'cert.src');
// E. Read from the path, and add the values to the certificate, also associate
// the certificate with the current request.
async.mapValues({
pfx: pfxPath,
key: keyPath,
cert: certPath
}, function (value, key, next) {
// bail out if value is not defined
// @todo add test with server which only accepts cert file
if (!value) { return next(); }
// eslint-disable-next-line security/detect-non-literal-fs-filename
fileResolver.readFile(value, function (err, data) {
// Swallow the error after triggering a warning message for the user.
err && run.triggers.console(context.coords, 'warn',
`certificate "${key}" load error: ${(err.message || err)}`);
next(null, data);
});
}, function (err, fileContents) {
if (err) {
// Swallow the error after triggering a warning message for the user.
run.triggers.console(context.coords, 'warn', 'certificate load error: ' + (err.message || err));
return done();
}
if (fileContents) {
!_.isNil(fileContents.pfx) && _.set(certificate, 'pfx.value', fileContents.pfx);
!_.isNil(fileContents.key) && _.set(certificate, 'key.value', fileContents.key);
!_.isNil(fileContents.cert) && _.set(certificate, 'cert.value', fileContents.cert);
(fileContents.cert || fileContents.key || fileContents.pfx) && (request.certificate = certificate);
}
done();
});
}
|
javascript
|
function (context, run, done) {
var request,
pfxPath,
keyPath,
certPath,
fileResolver,
certificate;
// A. Check if we have the file resolver
fileResolver = run.options.fileResolver;
if (!fileResolver) { return done(); } // No point going ahead
// B. Ensure we have the request
request = _.get(context.item, 'request');
if (!request) { return done(new Error('No request to resolve certificates for.')); }
// C. See if any cert should be sent, by performing a URL matching
certificate = run.options.certificates && run.options.certificates.resolveOne(request.url);
if (!certificate) { return done(); }
// D. Fetch the paths
// @todo: check why aren't we reading ca file (why are we not supporting ca file)
pfxPath = _.get(certificate, 'pfx.src');
keyPath = _.get(certificate, 'key.src');
certPath = _.get(certificate, 'cert.src');
// E. Read from the path, and add the values to the certificate, also associate
// the certificate with the current request.
async.mapValues({
pfx: pfxPath,
key: keyPath,
cert: certPath
}, function (value, key, next) {
// bail out if value is not defined
// @todo add test with server which only accepts cert file
if (!value) { return next(); }
// eslint-disable-next-line security/detect-non-literal-fs-filename
fileResolver.readFile(value, function (err, data) {
// Swallow the error after triggering a warning message for the user.
err && run.triggers.console(context.coords, 'warn',
`certificate "${key}" load error: ${(err.message || err)}`);
next(null, data);
});
}, function (err, fileContents) {
if (err) {
// Swallow the error after triggering a warning message for the user.
run.triggers.console(context.coords, 'warn', 'certificate load error: ' + (err.message || err));
return done();
}
if (fileContents) {
!_.isNil(fileContents.pfx) && _.set(certificate, 'pfx.value', fileContents.pfx);
!_.isNil(fileContents.key) && _.set(certificate, 'key.value', fileContents.key);
!_.isNil(fileContents.cert) && _.set(certificate, 'cert.value', fileContents.cert);
(fileContents.cert || fileContents.key || fileContents.pfx) && (request.certificate = certificate);
}
done();
});
}
|
[
"function",
"(",
"context",
",",
"run",
",",
"done",
")",
"{",
"var",
"request",
",",
"pfxPath",
",",
"keyPath",
",",
"certPath",
",",
"fileResolver",
",",
"certificate",
";",
"// A. Check if we have the file resolver",
"fileResolver",
"=",
"run",
".",
"options",
".",
"fileResolver",
";",
"if",
"(",
"!",
"fileResolver",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"// No point going ahead",
"// B. Ensure we have the request",
"request",
"=",
"_",
".",
"get",
"(",
"context",
".",
"item",
",",
"'request'",
")",
";",
"if",
"(",
"!",
"request",
")",
"{",
"return",
"done",
"(",
"new",
"Error",
"(",
"'No request to resolve certificates for.'",
")",
")",
";",
"}",
"// C. See if any cert should be sent, by performing a URL matching",
"certificate",
"=",
"run",
".",
"options",
".",
"certificates",
"&&",
"run",
".",
"options",
".",
"certificates",
".",
"resolveOne",
"(",
"request",
".",
"url",
")",
";",
"if",
"(",
"!",
"certificate",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"// D. Fetch the paths",
"// @todo: check why aren't we reading ca file (why are we not supporting ca file)",
"pfxPath",
"=",
"_",
".",
"get",
"(",
"certificate",
",",
"'pfx.src'",
")",
";",
"keyPath",
"=",
"_",
".",
"get",
"(",
"certificate",
",",
"'key.src'",
")",
";",
"certPath",
"=",
"_",
".",
"get",
"(",
"certificate",
",",
"'cert.src'",
")",
";",
"// E. Read from the path, and add the values to the certificate, also associate",
"// the certificate with the current request.",
"async",
".",
"mapValues",
"(",
"{",
"pfx",
":",
"pfxPath",
",",
"key",
":",
"keyPath",
",",
"cert",
":",
"certPath",
"}",
",",
"function",
"(",
"value",
",",
"key",
",",
"next",
")",
"{",
"// bail out if value is not defined",
"// @todo add test with server which only accepts cert file",
"if",
"(",
"!",
"value",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"// eslint-disable-next-line security/detect-non-literal-fs-filename",
"fileResolver",
".",
"readFile",
"(",
"value",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"// Swallow the error after triggering a warning message for the user.",
"err",
"&&",
"run",
".",
"triggers",
".",
"console",
"(",
"context",
".",
"coords",
",",
"'warn'",
",",
"`",
"${",
"key",
"}",
"${",
"(",
"err",
".",
"message",
"||",
"err",
")",
"}",
"`",
")",
";",
"next",
"(",
"null",
",",
"data",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
",",
"fileContents",
")",
"{",
"if",
"(",
"err",
")",
"{",
"// Swallow the error after triggering a warning message for the user.",
"run",
".",
"triggers",
".",
"console",
"(",
"context",
".",
"coords",
",",
"'warn'",
",",
"'certificate load error: '",
"+",
"(",
"err",
".",
"message",
"||",
"err",
")",
")",
";",
"return",
"done",
"(",
")",
";",
"}",
"if",
"(",
"fileContents",
")",
"{",
"!",
"_",
".",
"isNil",
"(",
"fileContents",
".",
"pfx",
")",
"&&",
"_",
".",
"set",
"(",
"certificate",
",",
"'pfx.value'",
",",
"fileContents",
".",
"pfx",
")",
";",
"!",
"_",
".",
"isNil",
"(",
"fileContents",
".",
"key",
")",
"&&",
"_",
".",
"set",
"(",
"certificate",
",",
"'key.value'",
",",
"fileContents",
".",
"key",
")",
";",
"!",
"_",
".",
"isNil",
"(",
"fileContents",
".",
"cert",
")",
"&&",
"_",
".",
"set",
"(",
"certificate",
",",
"'cert.value'",
",",
"fileContents",
".",
"cert",
")",
";",
"(",
"fileContents",
".",
"cert",
"||",
"fileContents",
".",
"key",
"||",
"fileContents",
".",
"pfx",
")",
"&&",
"(",
"request",
".",
"certificate",
"=",
"certificate",
")",
";",
"}",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Certificate lookup + reading from whichever file resolver is provided
|
[
"Certificate",
"lookup",
"+",
"reading",
"from",
"whichever",
"file",
"resolver",
"is",
"provided"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/request-helpers-presend.js#L319-L382
|
|
9,943
|
postmanlabs/postman-runtime
|
lib/backpack/index.js
|
function (cb, expect) {
if (_.isFunction(cb) && cb.__normalised) {
return meetExpectations(cb, expect);
}
var userback, // this var will be populated and returned
// keep a reference of all initial callbacks sent by user
callback = (_.isFunction(cb) && cb) || (_.isFunction(cb && cb.done) && cb.done),
callbackError = _.isFunction(cb && cb.error) && cb.error,
callbackSuccess = _.isFunction(cb && cb.success) && cb.success;
// create master callback that calls these user provided callbacks
userback = _.assign(function (err) {
// if common callback is defined, call that
callback && callback.apply(this, arguments);
// for special error and success, call them if they are user defined
if (err) {
callbackError && callbackError.apply(this, arguments);
}
else {
// remove the extra error param before calling success
callbackSuccess && callbackSuccess.apply(this, (Array.prototype.shift.call(arguments), arguments));
}
}, _.isPlainObject(cb) && cb, { // override error, success and done
error: function () {
return userback.apply(this, arguments);
},
success: function () {
// inject null to arguments and call the main callback
userback.apply(this, (Array.prototype.unshift.call(arguments, null), arguments));
},
done: function () {
return userback.apply(this, arguments);
},
__normalised: true
});
return meetExpectations(userback, expect);
}
|
javascript
|
function (cb, expect) {
if (_.isFunction(cb) && cb.__normalised) {
return meetExpectations(cb, expect);
}
var userback, // this var will be populated and returned
// keep a reference of all initial callbacks sent by user
callback = (_.isFunction(cb) && cb) || (_.isFunction(cb && cb.done) && cb.done),
callbackError = _.isFunction(cb && cb.error) && cb.error,
callbackSuccess = _.isFunction(cb && cb.success) && cb.success;
// create master callback that calls these user provided callbacks
userback = _.assign(function (err) {
// if common callback is defined, call that
callback && callback.apply(this, arguments);
// for special error and success, call them if they are user defined
if (err) {
callbackError && callbackError.apply(this, arguments);
}
else {
// remove the extra error param before calling success
callbackSuccess && callbackSuccess.apply(this, (Array.prototype.shift.call(arguments), arguments));
}
}, _.isPlainObject(cb) && cb, { // override error, success and done
error: function () {
return userback.apply(this, arguments);
},
success: function () {
// inject null to arguments and call the main callback
userback.apply(this, (Array.prototype.unshift.call(arguments, null), arguments));
},
done: function () {
return userback.apply(this, arguments);
},
__normalised: true
});
return meetExpectations(userback, expect);
}
|
[
"function",
"(",
"cb",
",",
"expect",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"cb",
")",
"&&",
"cb",
".",
"__normalised",
")",
"{",
"return",
"meetExpectations",
"(",
"cb",
",",
"expect",
")",
";",
"}",
"var",
"userback",
",",
"// this var will be populated and returned",
"// keep a reference of all initial callbacks sent by user",
"callback",
"=",
"(",
"_",
".",
"isFunction",
"(",
"cb",
")",
"&&",
"cb",
")",
"||",
"(",
"_",
".",
"isFunction",
"(",
"cb",
"&&",
"cb",
".",
"done",
")",
"&&",
"cb",
".",
"done",
")",
",",
"callbackError",
"=",
"_",
".",
"isFunction",
"(",
"cb",
"&&",
"cb",
".",
"error",
")",
"&&",
"cb",
".",
"error",
",",
"callbackSuccess",
"=",
"_",
".",
"isFunction",
"(",
"cb",
"&&",
"cb",
".",
"success",
")",
"&&",
"cb",
".",
"success",
";",
"// create master callback that calls these user provided callbacks",
"userback",
"=",
"_",
".",
"assign",
"(",
"function",
"(",
"err",
")",
"{",
"// if common callback is defined, call that",
"callback",
"&&",
"callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"// for special error and success, call them if they are user defined",
"if",
"(",
"err",
")",
"{",
"callbackError",
"&&",
"callbackError",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"// remove the extra error param before calling success",
"callbackSuccess",
"&&",
"callbackSuccess",
".",
"apply",
"(",
"this",
",",
"(",
"Array",
".",
"prototype",
".",
"shift",
".",
"call",
"(",
"arguments",
")",
",",
"arguments",
")",
")",
";",
"}",
"}",
",",
"_",
".",
"isPlainObject",
"(",
"cb",
")",
"&&",
"cb",
",",
"{",
"// override error, success and done",
"error",
":",
"function",
"(",
")",
"{",
"return",
"userback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
",",
"success",
":",
"function",
"(",
")",
"{",
"// inject null to arguments and call the main callback",
"userback",
".",
"apply",
"(",
"this",
",",
"(",
"Array",
".",
"prototype",
".",
"unshift",
".",
"call",
"(",
"arguments",
",",
"null",
")",
",",
"arguments",
")",
")",
";",
"}",
",",
"done",
":",
"function",
"(",
")",
"{",
"return",
"userback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
",",
"__normalised",
":",
"true",
"}",
")",
";",
"return",
"meetExpectations",
"(",
"userback",
",",
"expect",
")",
";",
"}"
] |
accept the callback parameter and convert it into a consistent object interface
@param {Function|Object} cb
@param {Array} [expect=]
@returns {Object}
@todo - write tests
|
[
"accept",
"the",
"callback",
"parameter",
"and",
"convert",
"it",
"into",
"a",
"consistent",
"object",
"interface"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/backpack/index.js#L44-L83
|
|
9,944
|
postmanlabs/postman-runtime
|
lib/backpack/index.js
|
function (flags, callback, args, ms) {
var status = {},
sealed;
// ensure that the callback times out after a while
callback = backpack.timeback(callback, ms, null, function () {
sealed = true;
});
return function (err, flag, value) {
if (sealed) { return; } // do not proceed of it is sealed
status[flag] = value;
if (err) { // on error we directly call the callback and seal subsequent calls
sealed = true;
status = null;
callback.call(status, err);
return;
}
// if any flag is not defined, we exit. when all flags hold a value, we know that the end callback has to be
// executed.
for (var i = 0, ii = flags.length; i < ii; i++) {
if (!status.hasOwnProperty(flags[i])) { return; }
}
sealed = true;
status = null;
callback.apply(status, args);
};
}
|
javascript
|
function (flags, callback, args, ms) {
var status = {},
sealed;
// ensure that the callback times out after a while
callback = backpack.timeback(callback, ms, null, function () {
sealed = true;
});
return function (err, flag, value) {
if (sealed) { return; } // do not proceed of it is sealed
status[flag] = value;
if (err) { // on error we directly call the callback and seal subsequent calls
sealed = true;
status = null;
callback.call(status, err);
return;
}
// if any flag is not defined, we exit. when all flags hold a value, we know that the end callback has to be
// executed.
for (var i = 0, ii = flags.length; i < ii; i++) {
if (!status.hasOwnProperty(flags[i])) { return; }
}
sealed = true;
status = null;
callback.apply(status, args);
};
}
|
[
"function",
"(",
"flags",
",",
"callback",
",",
"args",
",",
"ms",
")",
"{",
"var",
"status",
"=",
"{",
"}",
",",
"sealed",
";",
"// ensure that the callback times out after a while",
"callback",
"=",
"backpack",
".",
"timeback",
"(",
"callback",
",",
"ms",
",",
"null",
",",
"function",
"(",
")",
"{",
"sealed",
"=",
"true",
";",
"}",
")",
";",
"return",
"function",
"(",
"err",
",",
"flag",
",",
"value",
")",
"{",
"if",
"(",
"sealed",
")",
"{",
"return",
";",
"}",
"// do not proceed of it is sealed",
"status",
"[",
"flag",
"]",
"=",
"value",
";",
"if",
"(",
"err",
")",
"{",
"// on error we directly call the callback and seal subsequent calls",
"sealed",
"=",
"true",
";",
"status",
"=",
"null",
";",
"callback",
".",
"call",
"(",
"status",
",",
"err",
")",
";",
"return",
";",
"}",
"// if any flag is not defined, we exit. when all flags hold a value, we know that the end callback has to be",
"// executed.",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ii",
"=",
"flags",
".",
"length",
";",
"i",
"<",
"ii",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"status",
".",
"hasOwnProperty",
"(",
"flags",
"[",
"i",
"]",
")",
")",
"{",
"return",
";",
"}",
"}",
"sealed",
"=",
"true",
";",
"status",
"=",
"null",
";",
"callback",
".",
"apply",
"(",
"status",
",",
"args",
")",
";",
"}",
";",
"}"
] |
Convert a callback into a function that is called multiple times and the callback is actually called when a set
of flags are set to true
@param {Array} flags
@param {Function} callback
@param {Array} args
@param {Number} ms
@returns {Function}
|
[
"Convert",
"a",
"callback",
"into",
"a",
"function",
"that",
"is",
"called",
"multiple",
"times",
"and",
"the",
"callback",
"is",
"actually",
"called",
"when",
"a",
"set",
"of",
"flags",
"are",
"set",
"to",
"true"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/backpack/index.js#L95-L126
|
|
9,945
|
postmanlabs/postman-runtime
|
lib/backpack/index.js
|
function (callback, ms, scope, when) {
ms = Number(ms);
// if np callback time is specified, just return the callback function and exit. this is because we do need to
// track timeout in 0ms
if (!ms) {
return callback;
}
var sealed = false,
irq = setTimeout(function () { // irq = interrupt request
sealed = true;
irq = null;
when && when.call(scope || this);
callback.call(scope || this, new Error('callback timed out'));
}, ms);
return function () {
// if sealed, it means that timeout has elapsed and we accept no future callback
if (sealed) { return undefined; }
// otherwise we clear timeout and allow the callback to be executed. note that we do not seal the function
// since we should allow multiple callback calls.
irq && (irq = clearTimeout(irq));
return callback.apply(scope || this, arguments);
};
}
|
javascript
|
function (callback, ms, scope, when) {
ms = Number(ms);
// if np callback time is specified, just return the callback function and exit. this is because we do need to
// track timeout in 0ms
if (!ms) {
return callback;
}
var sealed = false,
irq = setTimeout(function () { // irq = interrupt request
sealed = true;
irq = null;
when && when.call(scope || this);
callback.call(scope || this, new Error('callback timed out'));
}, ms);
return function () {
// if sealed, it means that timeout has elapsed and we accept no future callback
if (sealed) { return undefined; }
// otherwise we clear timeout and allow the callback to be executed. note that we do not seal the function
// since we should allow multiple callback calls.
irq && (irq = clearTimeout(irq));
return callback.apply(scope || this, arguments);
};
}
|
[
"function",
"(",
"callback",
",",
"ms",
",",
"scope",
",",
"when",
")",
"{",
"ms",
"=",
"Number",
"(",
"ms",
")",
";",
"// if np callback time is specified, just return the callback function and exit. this is because we do need to",
"// track timeout in 0ms",
"if",
"(",
"!",
"ms",
")",
"{",
"return",
"callback",
";",
"}",
"var",
"sealed",
"=",
"false",
",",
"irq",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"// irq = interrupt request",
"sealed",
"=",
"true",
";",
"irq",
"=",
"null",
";",
"when",
"&&",
"when",
".",
"call",
"(",
"scope",
"||",
"this",
")",
";",
"callback",
".",
"call",
"(",
"scope",
"||",
"this",
",",
"new",
"Error",
"(",
"'callback timed out'",
")",
")",
";",
"}",
",",
"ms",
")",
";",
"return",
"function",
"(",
")",
"{",
"// if sealed, it means that timeout has elapsed and we accept no future callback",
"if",
"(",
"sealed",
")",
"{",
"return",
"undefined",
";",
"}",
"// otherwise we clear timeout and allow the callback to be executed. note that we do not seal the function",
"// since we should allow multiple callback calls.",
"irq",
"&&",
"(",
"irq",
"=",
"clearTimeout",
"(",
"irq",
")",
")",
";",
"return",
"callback",
".",
"apply",
"(",
"scope",
"||",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
] |
Ensures that a callback is executed within a specific time.
@param {Function} callback
@param {Number=} [ms]
@param {Object=} [scope]
@param {Function=} [when] - function executed right before callback is called with timeout. one can do cleanup
stuff here
@returns {Function}
|
[
"Ensures",
"that",
"a",
"callback",
"is",
"executed",
"within",
"a",
"specific",
"time",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/backpack/index.js#L138-L165
|
|
9,946
|
postmanlabs/postman-runtime
|
lib/runner/index.js
|
function (options) {
// combine runner config and make a copy
var runOptions = _.merge(_.omit(options, ['environment', 'globals', 'data']), this.options.run) || {};
// start timeout sanitization
!runOptions.timeout && (runOptions.timeout = {});
_.mergeWith(runOptions.timeout, defaultTimeouts, function (userTimeout, defaultTimeout) {
// non numbers, Infinity and missing values are set to default
if (!_.isFinite(userTimeout)) { return defaultTimeout; }
// 0 and negative numbers are set to Infinity, which only leaves positive numbers
return userTimeout > 0 ? userTimeout : Infinity;
});
return runOptions;
}
|
javascript
|
function (options) {
// combine runner config and make a copy
var runOptions = _.merge(_.omit(options, ['environment', 'globals', 'data']), this.options.run) || {};
// start timeout sanitization
!runOptions.timeout && (runOptions.timeout = {});
_.mergeWith(runOptions.timeout, defaultTimeouts, function (userTimeout, defaultTimeout) {
// non numbers, Infinity and missing values are set to default
if (!_.isFinite(userTimeout)) { return defaultTimeout; }
// 0 and negative numbers are set to Infinity, which only leaves positive numbers
return userTimeout > 0 ? userTimeout : Infinity;
});
return runOptions;
}
|
[
"function",
"(",
"options",
")",
"{",
"// combine runner config and make a copy",
"var",
"runOptions",
"=",
"_",
".",
"merge",
"(",
"_",
".",
"omit",
"(",
"options",
",",
"[",
"'environment'",
",",
"'globals'",
",",
"'data'",
"]",
")",
",",
"this",
".",
"options",
".",
"run",
")",
"||",
"{",
"}",
";",
"// start timeout sanitization",
"!",
"runOptions",
".",
"timeout",
"&&",
"(",
"runOptions",
".",
"timeout",
"=",
"{",
"}",
")",
";",
"_",
".",
"mergeWith",
"(",
"runOptions",
".",
"timeout",
",",
"defaultTimeouts",
",",
"function",
"(",
"userTimeout",
",",
"defaultTimeout",
")",
"{",
"// non numbers, Infinity and missing values are set to default",
"if",
"(",
"!",
"_",
".",
"isFinite",
"(",
"userTimeout",
")",
")",
"{",
"return",
"defaultTimeout",
";",
"}",
"// 0 and negative numbers are set to Infinity, which only leaves positive numbers",
"return",
"userTimeout",
">",
"0",
"?",
"userTimeout",
":",
"Infinity",
";",
"}",
")",
";",
"return",
"runOptions",
";",
"}"
] |
Prepares `run` config by combining `runner` config with given run options.
@param {Object} [options]
@param {Object} [options.timeout]
@param {Object} [options.timeout.global]
@param {Object} [options.timeout.request]
@param {Object} [options.timeout.script]
|
[
"Prepares",
"run",
"config",
"by",
"combining",
"runner",
"config",
"with",
"given",
"run",
"options",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/index.js#L40-L56
|
|
9,947
|
postmanlabs/postman-runtime
|
lib/runner/index.js
|
function (collection, options, callback) {
var self = this,
runOptions = this.prepareRunConfig(options);
callback = backpack.normalise(callback);
!_.isObject(options) && (options = {});
// @todo make the extract runnables interface better defined and documented
// - give the ownership of error to each strategy lookup functions
// - think about moving these codes into an extension command prior to waterfall
// - the third argument in callback that returns control, is ambiguous and can be removed if error is controlled
// by each lookup function.
// - the interface can be further broken down to have the "flattenNode" action be made common and not be
// required to be coded in each lookup strategy
//
// serialise the items into a linear array based on the lookup strategy provided as input
extractRunnableItems(collection, options.entrypoint, function (err, runnableItems, entrypoint) {
if (err || !runnableItems) { return callback(new Error('Error fetching run items')); }
// Bail out only if: abortOnError is set and the returned entrypoint is invalid
if (options.abortOnError && !entrypoint) {
// eslint-disable-next-line max-len
return callback(new Error(`Unable to find a folder or request: ${_.get(options, 'entrypoint.execute')}`));
}
return callback(null, (new Run({
items: runnableItems,
data: Runner.normaliseIterationData(options.data, options.iterationCount),
environment: options.environment,
globals: _.has(options, 'globals') ? options.globals : self.options.globals,
// @todo Move to item level to support Item and ItemGroup variables
collectionVariables: collection.variables,
certificates: options.certificates,
proxies: options.proxies
}, runOptions)));
});
}
|
javascript
|
function (collection, options, callback) {
var self = this,
runOptions = this.prepareRunConfig(options);
callback = backpack.normalise(callback);
!_.isObject(options) && (options = {});
// @todo make the extract runnables interface better defined and documented
// - give the ownership of error to each strategy lookup functions
// - think about moving these codes into an extension command prior to waterfall
// - the third argument in callback that returns control, is ambiguous and can be removed if error is controlled
// by each lookup function.
// - the interface can be further broken down to have the "flattenNode" action be made common and not be
// required to be coded in each lookup strategy
//
// serialise the items into a linear array based on the lookup strategy provided as input
extractRunnableItems(collection, options.entrypoint, function (err, runnableItems, entrypoint) {
if (err || !runnableItems) { return callback(new Error('Error fetching run items')); }
// Bail out only if: abortOnError is set and the returned entrypoint is invalid
if (options.abortOnError && !entrypoint) {
// eslint-disable-next-line max-len
return callback(new Error(`Unable to find a folder or request: ${_.get(options, 'entrypoint.execute')}`));
}
return callback(null, (new Run({
items: runnableItems,
data: Runner.normaliseIterationData(options.data, options.iterationCount),
environment: options.environment,
globals: _.has(options, 'globals') ? options.globals : self.options.globals,
// @todo Move to item level to support Item and ItemGroup variables
collectionVariables: collection.variables,
certificates: options.certificates,
proxies: options.proxies
}, runOptions)));
});
}
|
[
"function",
"(",
"collection",
",",
"options",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
",",
"runOptions",
"=",
"this",
".",
"prepareRunConfig",
"(",
"options",
")",
";",
"callback",
"=",
"backpack",
".",
"normalise",
"(",
"callback",
")",
";",
"!",
"_",
".",
"isObject",
"(",
"options",
")",
"&&",
"(",
"options",
"=",
"{",
"}",
")",
";",
"// @todo make the extract runnables interface better defined and documented",
"// - give the ownership of error to each strategy lookup functions",
"// - think about moving these codes into an extension command prior to waterfall",
"// - the third argument in callback that returns control, is ambiguous and can be removed if error is controlled",
"// by each lookup function.",
"// - the interface can be further broken down to have the \"flattenNode\" action be made common and not be",
"// required to be coded in each lookup strategy",
"//",
"// serialise the items into a linear array based on the lookup strategy provided as input",
"extractRunnableItems",
"(",
"collection",
",",
"options",
".",
"entrypoint",
",",
"function",
"(",
"err",
",",
"runnableItems",
",",
"entrypoint",
")",
"{",
"if",
"(",
"err",
"||",
"!",
"runnableItems",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Error fetching run items'",
")",
")",
";",
"}",
"// Bail out only if: abortOnError is set and the returned entrypoint is invalid",
"if",
"(",
"options",
".",
"abortOnError",
"&&",
"!",
"entrypoint",
")",
"{",
"// eslint-disable-next-line max-len",
"return",
"callback",
"(",
"new",
"Error",
"(",
"`",
"${",
"_",
".",
"get",
"(",
"options",
",",
"'entrypoint.execute'",
")",
"}",
"`",
")",
")",
";",
"}",
"return",
"callback",
"(",
"null",
",",
"(",
"new",
"Run",
"(",
"{",
"items",
":",
"runnableItems",
",",
"data",
":",
"Runner",
".",
"normaliseIterationData",
"(",
"options",
".",
"data",
",",
"options",
".",
"iterationCount",
")",
",",
"environment",
":",
"options",
".",
"environment",
",",
"globals",
":",
"_",
".",
"has",
"(",
"options",
",",
"'globals'",
")",
"?",
"options",
".",
"globals",
":",
"self",
".",
"options",
".",
"globals",
",",
"// @todo Move to item level to support Item and ItemGroup variables",
"collectionVariables",
":",
"collection",
".",
"variables",
",",
"certificates",
":",
"options",
".",
"certificates",
",",
"proxies",
":",
"options",
".",
"proxies",
"}",
",",
"runOptions",
")",
")",
")",
";",
"}",
")",
";",
"}"
] |
Runs a collection or a folder.
@param {Collection} collection
@param {Object} [options]
@param {Array.<Item>} options.items
@param {Array.<Object>} [options.data]
@param {Object} [options.globals]
@param {Object} [options.environment]
@param {Number} [options.iterationCount]
@param {CertificateList} [options.certificates]
@param {ProxyConfigList} [options.proxies]
@param {Array} [options.data]
@param {Object} [options.entrypoint]
@param {String} [options.entrypoint.execute] ID of the item-group to be run.
Can be Name if `entrypoint.lookupStrategy` is `idOrName`
@param {String} [options.entrypoint.lookupStrategy=idOrName] strategy to lookup the entrypoint [idOrName, path]
@param {Array<String>} [options.entrypoint.path] path to lookup
@param {Object} [options.run] Run-specific options, such as options related to the host
@param {Function} callback
|
[
"Runs",
"a",
"collection",
"or",
"a",
"folder",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/index.js#L80-L116
|
|
9,948
|
postmanlabs/postman-runtime
|
lib/runner/extensions/control.command.js
|
function (callback) {
callback = backpack.ensure(callback, this);
if (this.paused) { return callback && callback(new Error('run: already paused')); }
// schedule the pause command as an interrupt and flag that the run is pausing
this.paused = true;
this.interrupt('pause', null, callback);
}
|
javascript
|
function (callback) {
callback = backpack.ensure(callback, this);
if (this.paused) { return callback && callback(new Error('run: already paused')); }
// schedule the pause command as an interrupt and flag that the run is pausing
this.paused = true;
this.interrupt('pause', null, callback);
}
|
[
"function",
"(",
"callback",
")",
"{",
"callback",
"=",
"backpack",
".",
"ensure",
"(",
"callback",
",",
"this",
")",
";",
"if",
"(",
"this",
".",
"paused",
")",
"{",
"return",
"callback",
"&&",
"callback",
"(",
"new",
"Error",
"(",
"'run: already paused'",
")",
")",
";",
"}",
"// schedule the pause command as an interrupt and flag that the run is pausing",
"this",
".",
"paused",
"=",
"true",
";",
"this",
".",
"interrupt",
"(",
"'pause'",
",",
"null",
",",
"callback",
")",
";",
"}"
] |
Pause a run
@param {Function} callback
|
[
"Pause",
"a",
"run"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/extensions/control.command.js#L18-L26
|
|
9,949
|
postmanlabs/postman-runtime
|
lib/runner/extensions/control.command.js
|
function (callback) {
callback = backpack.ensure(callback, this);
if (!this.paused) { return callback && callback(new Error('run: not paused')); }
// set flag that it is no longer paused and fire the stored callback for the command when it was paused
this.paused = false;
setTimeout(function () {
this.__resume();
delete this.__resume;
this.triggers.resume(null, this.state.cursor.current());
}.bind(this), 0);
callback && callback();
}
|
javascript
|
function (callback) {
callback = backpack.ensure(callback, this);
if (!this.paused) { return callback && callback(new Error('run: not paused')); }
// set flag that it is no longer paused and fire the stored callback for the command when it was paused
this.paused = false;
setTimeout(function () {
this.__resume();
delete this.__resume;
this.triggers.resume(null, this.state.cursor.current());
}.bind(this), 0);
callback && callback();
}
|
[
"function",
"(",
"callback",
")",
"{",
"callback",
"=",
"backpack",
".",
"ensure",
"(",
"callback",
",",
"this",
")",
";",
"if",
"(",
"!",
"this",
".",
"paused",
")",
"{",
"return",
"callback",
"&&",
"callback",
"(",
"new",
"Error",
"(",
"'run: not paused'",
")",
")",
";",
"}",
"// set flag that it is no longer paused and fire the stored callback for the command when it was paused",
"this",
".",
"paused",
"=",
"false",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"this",
".",
"__resume",
"(",
")",
";",
"delete",
"this",
".",
"__resume",
";",
"this",
".",
"triggers",
".",
"resume",
"(",
"null",
",",
"this",
".",
"state",
".",
"cursor",
".",
"current",
"(",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
",",
"0",
")",
";",
"callback",
"&&",
"callback",
"(",
")",
";",
"}"
] |
Resume a paused a run
@param {Function} callback
|
[
"Resume",
"a",
"paused",
"a",
"run"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/extensions/control.command.js#L33-L47
|
|
9,950
|
postmanlabs/postman-runtime
|
lib/runner/extensions/control.command.js
|
function (summarise, callback) {
if (_.isFunction(summarise) && !callback) {
callback = summarise;
summarise = true;
}
this.interrupt('abort', {
summarise: summarise
}, callback);
_.isFunction(this.__resume) && this.resume();
}
|
javascript
|
function (summarise, callback) {
if (_.isFunction(summarise) && !callback) {
callback = summarise;
summarise = true;
}
this.interrupt('abort', {
summarise: summarise
}, callback);
_.isFunction(this.__resume) && this.resume();
}
|
[
"function",
"(",
"summarise",
",",
"callback",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"summarise",
")",
"&&",
"!",
"callback",
")",
"{",
"callback",
"=",
"summarise",
";",
"summarise",
"=",
"true",
";",
"}",
"this",
".",
"interrupt",
"(",
"'abort'",
",",
"{",
"summarise",
":",
"summarise",
"}",
",",
"callback",
")",
";",
"_",
".",
"isFunction",
"(",
"this",
".",
"__resume",
")",
"&&",
"this",
".",
"resume",
"(",
")",
";",
"}"
] |
Aborts a run
@param {boolean} [summarise=true]
@param {function} callback
|
[
"Aborts",
"a",
"run"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/extensions/control.command.js#L55-L66
|
|
9,951
|
postmanlabs/postman-runtime
|
lib/runner/cursor.js
|
function (callback, scope) {
var coords = _.isFunction(callback) && this.current();
this.position = 0;
this.iteration = 0;
// send before and after values to the callback
return coords && callback.call(scope || this, null, this.current(), coords);
}
|
javascript
|
function (callback, scope) {
var coords = _.isFunction(callback) && this.current();
this.position = 0;
this.iteration = 0;
// send before and after values to the callback
return coords && callback.call(scope || this, null, this.current(), coords);
}
|
[
"function",
"(",
"callback",
",",
"scope",
")",
"{",
"var",
"coords",
"=",
"_",
".",
"isFunction",
"(",
"callback",
")",
"&&",
"this",
".",
"current",
"(",
")",
";",
"this",
".",
"position",
"=",
"0",
";",
"this",
".",
"iteration",
"=",
"0",
";",
"// send before and after values to the callback",
"return",
"coords",
"&&",
"callback",
".",
"call",
"(",
"scope",
"||",
"this",
",",
"null",
",",
"this",
".",
"current",
"(",
")",
",",
"coords",
")",
";",
"}"
] |
Set everything to minimum dimension
@param {Function} [callback] - receives `(err:Error, coords:Object, previous:Object)`
@param {Object} [scope]
|
[
"Set",
"everything",
"to",
"minimum",
"dimension"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/cursor.js#L98-L106
|
|
9,952
|
postmanlabs/postman-runtime
|
lib/runner/cursor.js
|
function (position, iteration, callback, scope) {
var coords = _.isFunction(callback) && this.current();
// if null or undefined implies use existing seek position
_.isNil(position) && (position = this.position);
_.isNil(iteration) && (iteration = this.iteration);
// make the pointers stay within boundary
if ((position >= this.length) || (iteration >= this.cycles) || (position < 0) || (iteration < 0) ||
isNaN(position) || isNaN(iteration)) {
return coords &&
callback.call(scope || this, new Error('runcursor: seeking out of bounds: ' + [position, iteration]));
}
// floor the numbers
position = ~~position;
iteration = ~~iteration;
// set the new positions
this.position = Cursor.validate(position, 0, this.length);
this.iteration = Cursor.validate(iteration, 0, this.cycles);
// finally execute the callback with the seek position
return coords && callback.call(scope || this, null, this.hasChanged(coords), this.current(), coords);
}
|
javascript
|
function (position, iteration, callback, scope) {
var coords = _.isFunction(callback) && this.current();
// if null or undefined implies use existing seek position
_.isNil(position) && (position = this.position);
_.isNil(iteration) && (iteration = this.iteration);
// make the pointers stay within boundary
if ((position >= this.length) || (iteration >= this.cycles) || (position < 0) || (iteration < 0) ||
isNaN(position) || isNaN(iteration)) {
return coords &&
callback.call(scope || this, new Error('runcursor: seeking out of bounds: ' + [position, iteration]));
}
// floor the numbers
position = ~~position;
iteration = ~~iteration;
// set the new positions
this.position = Cursor.validate(position, 0, this.length);
this.iteration = Cursor.validate(iteration, 0, this.cycles);
// finally execute the callback with the seek position
return coords && callback.call(scope || this, null, this.hasChanged(coords), this.current(), coords);
}
|
[
"function",
"(",
"position",
",",
"iteration",
",",
"callback",
",",
"scope",
")",
"{",
"var",
"coords",
"=",
"_",
".",
"isFunction",
"(",
"callback",
")",
"&&",
"this",
".",
"current",
"(",
")",
";",
"// if null or undefined implies use existing seek position",
"_",
".",
"isNil",
"(",
"position",
")",
"&&",
"(",
"position",
"=",
"this",
".",
"position",
")",
";",
"_",
".",
"isNil",
"(",
"iteration",
")",
"&&",
"(",
"iteration",
"=",
"this",
".",
"iteration",
")",
";",
"// make the pointers stay within boundary",
"if",
"(",
"(",
"position",
">=",
"this",
".",
"length",
")",
"||",
"(",
"iteration",
">=",
"this",
".",
"cycles",
")",
"||",
"(",
"position",
"<",
"0",
")",
"||",
"(",
"iteration",
"<",
"0",
")",
"||",
"isNaN",
"(",
"position",
")",
"||",
"isNaN",
"(",
"iteration",
")",
")",
"{",
"return",
"coords",
"&&",
"callback",
".",
"call",
"(",
"scope",
"||",
"this",
",",
"new",
"Error",
"(",
"'runcursor: seeking out of bounds: '",
"+",
"[",
"position",
",",
"iteration",
"]",
")",
")",
";",
"}",
"// floor the numbers",
"position",
"=",
"~",
"~",
"position",
";",
"iteration",
"=",
"~",
"~",
"iteration",
";",
"// set the new positions",
"this",
".",
"position",
"=",
"Cursor",
".",
"validate",
"(",
"position",
",",
"0",
",",
"this",
".",
"length",
")",
";",
"this",
".",
"iteration",
"=",
"Cursor",
".",
"validate",
"(",
"iteration",
",",
"0",
",",
"this",
".",
"cycles",
")",
";",
"// finally execute the callback with the seek position",
"return",
"coords",
"&&",
"callback",
".",
"call",
"(",
"scope",
"||",
"this",
",",
"null",
",",
"this",
".",
"hasChanged",
"(",
"coords",
")",
",",
"this",
".",
"current",
"(",
")",
",",
"coords",
")",
";",
"}"
] |
Seek to a specified Cursor
@param {Number} [position]
@param {Number} [iteration]
@param {Function} [callback] - receives `(err:Error, changed:Boolean, coords:Object, previous:Object)`
@param {Object} [scope]
|
[
"Seek",
"to",
"a",
"specified",
"Cursor"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/cursor.js#L133-L157
|
|
9,953
|
postmanlabs/postman-runtime
|
lib/runner/cursor.js
|
function (callback, scope) {
var position = this.position,
iteration = this.iteration,
coords;
// increment position
position += 1;
// check if we need to increment cycle
if (position >= this.length) {
// set position to 0 and increment iteration
position = 0;
iteration += 1;
if (iteration >= this.cycles) {
coords = _.isFunction(callback) && this.current();
coords.eof = true;
return coords && callback.call(scope || this, null, false, coords, coords);
}
coords && (coords.cr = true);
}
// finally handover the new coordinates to seek function
return this.seek(position, iteration, callback, scope);
}
|
javascript
|
function (callback, scope) {
var position = this.position,
iteration = this.iteration,
coords;
// increment position
position += 1;
// check if we need to increment cycle
if (position >= this.length) {
// set position to 0 and increment iteration
position = 0;
iteration += 1;
if (iteration >= this.cycles) {
coords = _.isFunction(callback) && this.current();
coords.eof = true;
return coords && callback.call(scope || this, null, false, coords, coords);
}
coords && (coords.cr = true);
}
// finally handover the new coordinates to seek function
return this.seek(position, iteration, callback, scope);
}
|
[
"function",
"(",
"callback",
",",
"scope",
")",
"{",
"var",
"position",
"=",
"this",
".",
"position",
",",
"iteration",
"=",
"this",
".",
"iteration",
",",
"coords",
";",
"// increment position",
"position",
"+=",
"1",
";",
"// check if we need to increment cycle",
"if",
"(",
"position",
">=",
"this",
".",
"length",
")",
"{",
"// set position to 0 and increment iteration",
"position",
"=",
"0",
";",
"iteration",
"+=",
"1",
";",
"if",
"(",
"iteration",
">=",
"this",
".",
"cycles",
")",
"{",
"coords",
"=",
"_",
".",
"isFunction",
"(",
"callback",
")",
"&&",
"this",
".",
"current",
"(",
")",
";",
"coords",
".",
"eof",
"=",
"true",
";",
"return",
"coords",
"&&",
"callback",
".",
"call",
"(",
"scope",
"||",
"this",
",",
"null",
",",
"false",
",",
"coords",
",",
"coords",
")",
";",
"}",
"coords",
"&&",
"(",
"coords",
".",
"cr",
"=",
"true",
")",
";",
"}",
"// finally handover the new coordinates to seek function",
"return",
"this",
".",
"seek",
"(",
"position",
",",
"iteration",
",",
"callback",
",",
"scope",
")",
";",
"}"
] |
Seek one forward
@param {Function} [callback] - receives `(err:Error, changed:Boolean, coords:Object, previous:Object)`
@param {Object} [scope]
|
[
"Seek",
"one",
"forward"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/cursor.js#L165-L192
|
|
9,954
|
postmanlabs/postman-runtime
|
lib/runner/cursor.js
|
function (coords) {
return _.isObject(coords) && !((this.position === coords.position) && (this.iteration === coords.iteration));
}
|
javascript
|
function (coords) {
return _.isObject(coords) && !((this.position === coords.position) && (this.iteration === coords.iteration));
}
|
[
"function",
"(",
"coords",
")",
"{",
"return",
"_",
".",
"isObject",
"(",
"coords",
")",
"&&",
"!",
"(",
"(",
"this",
".",
"position",
"===",
"coords",
".",
"position",
")",
"&&",
"(",
"this",
".",
"iteration",
"===",
"coords",
".",
"iteration",
")",
")",
";",
"}"
] |
Check whether current position and iteration is not as the same specified
@param {Object} coords
@returns {Boolean}
|
[
"Check",
"whether",
"current",
"position",
"and",
"iteration",
"is",
"not",
"as",
"the",
"same",
"specified"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/cursor.js#L253-L255
|
|
9,955
|
postmanlabs/postman-runtime
|
lib/runner/cursor.js
|
function () {
return {
position: this.position,
iteration: this.iteration,
length: this.length,
cycles: this.cycles,
empty: this.empty(),
eof: this.eof(),
bof: this.bof(),
cr: this.cr(),
ref: this.ref
};
}
|
javascript
|
function () {
return {
position: this.position,
iteration: this.iteration,
length: this.length,
cycles: this.cycles,
empty: this.empty(),
eof: this.eof(),
bof: this.bof(),
cr: this.cr(),
ref: this.ref
};
}
|
[
"function",
"(",
")",
"{",
"return",
"{",
"position",
":",
"this",
".",
"position",
",",
"iteration",
":",
"this",
".",
"iteration",
",",
"length",
":",
"this",
".",
"length",
",",
"cycles",
":",
"this",
".",
"cycles",
",",
"empty",
":",
"this",
".",
"empty",
"(",
")",
",",
"eof",
":",
"this",
".",
"eof",
"(",
")",
",",
"bof",
":",
"this",
".",
"bof",
"(",
")",
",",
"cr",
":",
"this",
".",
"cr",
"(",
")",
",",
"ref",
":",
"this",
".",
"ref",
"}",
";",
"}"
] |
Current Cursor state
@returns {Object}
|
[
"Current",
"Cursor",
"state"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/cursor.js#L262-L274
|
|
9,956
|
postmanlabs/postman-runtime
|
lib/runner/instruction.js
|
function (name, payload, args) {
var processor = processors[name];
if (!_.isString(name) || !_.isFunction(processor)) {
throw new Error('run-instruction: invalid construction');
}
// ensure that payload is an object so that data storage can be done. also ensure arguments is an array
!_.isObject(payload) && (payload = {});
!_.isArray(args) && (args = []);
_.assign(this, /** @lends Instruction.prototype */ {
/**
* @type {String}
*/
action: name,
/**
* @type {Object}
*/
payload: payload,
/**
* @type {Array}
*/
in: args,
/**
* @type {Timings}
*/
timings: Timings.create(),
/**
* @private
* @type {Function}
*/
_processor: processor
});
// record the timing when this instruction was created
this.timings.record('created');
}
|
javascript
|
function (name, payload, args) {
var processor = processors[name];
if (!_.isString(name) || !_.isFunction(processor)) {
throw new Error('run-instruction: invalid construction');
}
// ensure that payload is an object so that data storage can be done. also ensure arguments is an array
!_.isObject(payload) && (payload = {});
!_.isArray(args) && (args = []);
_.assign(this, /** @lends Instruction.prototype */ {
/**
* @type {String}
*/
action: name,
/**
* @type {Object}
*/
payload: payload,
/**
* @type {Array}
*/
in: args,
/**
* @type {Timings}
*/
timings: Timings.create(),
/**
* @private
* @type {Function}
*/
_processor: processor
});
// record the timing when this instruction was created
this.timings.record('created');
}
|
[
"function",
"(",
"name",
",",
"payload",
",",
"args",
")",
"{",
"var",
"processor",
"=",
"processors",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"name",
")",
"||",
"!",
"_",
".",
"isFunction",
"(",
"processor",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'run-instruction: invalid construction'",
")",
";",
"}",
"// ensure that payload is an object so that data storage can be done. also ensure arguments is an array",
"!",
"_",
".",
"isObject",
"(",
"payload",
")",
"&&",
"(",
"payload",
"=",
"{",
"}",
")",
";",
"!",
"_",
".",
"isArray",
"(",
"args",
")",
"&&",
"(",
"args",
"=",
"[",
"]",
")",
";",
"_",
".",
"assign",
"(",
"this",
",",
"/** @lends Instruction.prototype */",
"{",
"/**\n * @type {String}\n */",
"action",
":",
"name",
",",
"/**\n * @type {Object}\n */",
"payload",
":",
"payload",
",",
"/**\n * @type {Array}\n */",
"in",
":",
"args",
",",
"/**\n * @type {Timings}\n */",
"timings",
":",
"Timings",
".",
"create",
"(",
")",
",",
"/**\n * @private\n * @type {Function}\n */",
"_processor",
":",
"processor",
"}",
")",
";",
"// record the timing when this instruction was created",
"this",
".",
"timings",
".",
"record",
"(",
"'created'",
")",
";",
"}"
] |
Create a new instruction to be executed later
@constructor
@param {String} name - name of the instruction. this is useful for later lookup of the `processor` function when
deserialising this object
@param {Object} [payload] - a **JSON compatible** object that will be forwarded as the 2nd last parameter to the
processor.
@param {Array} [args] - all the arguments that needs to be passed to the processor is in this array
@private
@example
var inst = Instruction.create(function (arg1, payload, next) {
console.log(payload);
next(null, 'hello-on-execute with ' + arg1);
}, 'sample-instruction', {
payloadData1: 'value'
}, ['one-arg']);
// now, when we do execute, the result will be a console.log of payload and message will be as expected
instance.execute(function (err, message) {
console.log(message);
});
|
[
"Create",
"a",
"new",
"instruction",
"to",
"be",
"executed",
"later"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/instruction.js#L49-L90
|
|
9,957
|
postmanlabs/postman-runtime
|
lib/requester/browser/request.js
|
is_crossDomain
|
function is_crossDomain(url) {
var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/
// jQuery #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
var ajaxLocation
try { ajaxLocation = location.href }
catch (e) {
// Use the href attribute of an A element since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []
, parts = rurl.exec(url.toLowerCase() )
var result = !!(
parts &&
( parts[1] != ajaxLocParts[1]
|| parts[2] != ajaxLocParts[2]
|| (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))
)
)
//console.debug('is_crossDomain('+url+') -> ' + result)
return result
}
|
javascript
|
function is_crossDomain(url) {
var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/
// jQuery #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
var ajaxLocation
try { ajaxLocation = location.href }
catch (e) {
// Use the href attribute of an A element since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []
, parts = rurl.exec(url.toLowerCase() )
var result = !!(
parts &&
( parts[1] != ajaxLocParts[1]
|| parts[2] != ajaxLocParts[2]
|| (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))
)
)
//console.debug('is_crossDomain('+url+') -> ' + result)
return result
}
|
[
"function",
"is_crossDomain",
"(",
"url",
")",
"{",
"var",
"rurl",
"=",
"/",
"^([\\w\\+\\.\\-]+:)(?:\\/\\/([^\\/?#:]*)(?::(\\d+))?)?",
"/",
"// jQuery #8138, IE may throw an exception when accessing",
"// a field from window.location if document.domain has been set",
"var",
"ajaxLocation",
"try",
"{",
"ajaxLocation",
"=",
"location",
".",
"href",
"}",
"catch",
"(",
"e",
")",
"{",
"// Use the href attribute of an A element since IE will modify it given document.location",
"ajaxLocation",
"=",
"document",
".",
"createElement",
"(",
"\"a\"",
")",
";",
"ajaxLocation",
".",
"href",
"=",
"\"\"",
";",
"ajaxLocation",
"=",
"ajaxLocation",
".",
"href",
";",
"}",
"var",
"ajaxLocParts",
"=",
"rurl",
".",
"exec",
"(",
"ajaxLocation",
".",
"toLowerCase",
"(",
")",
")",
"||",
"[",
"]",
",",
"parts",
"=",
"rurl",
".",
"exec",
"(",
"url",
".",
"toLowerCase",
"(",
")",
")",
"var",
"result",
"=",
"!",
"!",
"(",
"parts",
"&&",
"(",
"parts",
"[",
"1",
"]",
"!=",
"ajaxLocParts",
"[",
"1",
"]",
"||",
"parts",
"[",
"2",
"]",
"!=",
"ajaxLocParts",
"[",
"2",
"]",
"||",
"(",
"parts",
"[",
"3",
"]",
"||",
"(",
"parts",
"[",
"1",
"]",
"===",
"\"http:\"",
"?",
"80",
":",
"443",
")",
")",
"!=",
"(",
"ajaxLocParts",
"[",
"3",
"]",
"||",
"(",
"ajaxLocParts",
"[",
"1",
"]",
"===",
"\"http:\"",
"?",
"80",
":",
"443",
")",
")",
")",
")",
"//console.debug('is_crossDomain('+url+') -> ' + result)",
"return",
"result",
"}"
] |
Return whether a URL is a cross-domain request.
|
[
"Return",
"whether",
"a",
"URL",
"is",
"a",
"cross",
"-",
"domain",
"request",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/requester/browser/request.js#L456-L483
|
9,958
|
postmanlabs/postman-runtime
|
lib/authorizer/digest.js
|
_getDigestAuthHeader
|
function _getDigestAuthHeader (headers) {
return headers.find(function (property) {
return (property.key.toLowerCase() === WWW_AUTHENTICATE) && (_.startsWith(property.value, DIGEST_PREFIX));
});
}
|
javascript
|
function _getDigestAuthHeader (headers) {
return headers.find(function (property) {
return (property.key.toLowerCase() === WWW_AUTHENTICATE) && (_.startsWith(property.value, DIGEST_PREFIX));
});
}
|
[
"function",
"_getDigestAuthHeader",
"(",
"headers",
")",
"{",
"return",
"headers",
".",
"find",
"(",
"function",
"(",
"property",
")",
"{",
"return",
"(",
"property",
".",
"key",
".",
"toLowerCase",
"(",
")",
"===",
"WWW_AUTHENTICATE",
")",
"&&",
"(",
"_",
".",
"startsWith",
"(",
"property",
".",
"value",
",",
"DIGEST_PREFIX",
")",
")",
";",
"}",
")",
";",
"}"
] |
Returns the 'www-authenticate' header for Digest auth. Since a server can suport more than more auth-scheme,
there can be more than one header with the same key. So need to loop over and check each one.
@param {VariableList} headers
@private
|
[
"Returns",
"the",
"www",
"-",
"authenticate",
"header",
"for",
"Digest",
"auth",
".",
"Since",
"a",
"server",
"can",
"suport",
"more",
"than",
"more",
"auth",
"-",
"scheme",
"there",
"can",
"be",
"more",
"than",
"one",
"header",
"with",
"the",
"same",
"key",
".",
"So",
"need",
"to",
"loop",
"over",
"and",
"check",
"each",
"one",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/authorizer/digest.js#L89-L93
|
9,959
|
postmanlabs/postman-runtime
|
lib/authorizer/digest.js
|
function (auth, response, done) {
if (auth.get(DISABLE_RETRY_REQUEST) || !response) {
return done(null, true);
}
var code,
realm,
nonce,
qop,
opaque,
authHeader,
authParams = {};
code = response.code;
authHeader = _getDigestAuthHeader(response.headers);
// If code is forbidden or unauthorized, and an auth header exists,
// we can extract the realm & the nonce, and replay the request.
// todo: add response.is4XX, response.is5XX, etc in the SDK.
if ((code === 401 || code === 403) && authHeader) {
nonce = _extractField(authHeader.value, nonceRegex);
realm = _extractField(authHeader.value, realmRegex);
qop = _extractField(authHeader.value, qopRegex);
opaque = _extractField(authHeader.value, opaqueRegex);
authParams.nonce = nonce;
authParams.realm = realm;
opaque && (authParams.opaque = opaque);
qop && (authParams.qop = qop);
if (authParams.qop || auth.get(QOP)) {
authParams.clientNonce = randomString(8);
authParams.nonceCount = ONE;
}
// if all the auth parameters sent by server were already present in auth definition then we do not retry
if (_.every(authParams, function (value, key) { return auth.get(key); })) {
return done(null, true);
}
auth.set(authParams);
return done(null, false);
}
done(null, true);
}
|
javascript
|
function (auth, response, done) {
if (auth.get(DISABLE_RETRY_REQUEST) || !response) {
return done(null, true);
}
var code,
realm,
nonce,
qop,
opaque,
authHeader,
authParams = {};
code = response.code;
authHeader = _getDigestAuthHeader(response.headers);
// If code is forbidden or unauthorized, and an auth header exists,
// we can extract the realm & the nonce, and replay the request.
// todo: add response.is4XX, response.is5XX, etc in the SDK.
if ((code === 401 || code === 403) && authHeader) {
nonce = _extractField(authHeader.value, nonceRegex);
realm = _extractField(authHeader.value, realmRegex);
qop = _extractField(authHeader.value, qopRegex);
opaque = _extractField(authHeader.value, opaqueRegex);
authParams.nonce = nonce;
authParams.realm = realm;
opaque && (authParams.opaque = opaque);
qop && (authParams.qop = qop);
if (authParams.qop || auth.get(QOP)) {
authParams.clientNonce = randomString(8);
authParams.nonceCount = ONE;
}
// if all the auth parameters sent by server were already present in auth definition then we do not retry
if (_.every(authParams, function (value, key) { return auth.get(key); })) {
return done(null, true);
}
auth.set(authParams);
return done(null, false);
}
done(null, true);
}
|
[
"function",
"(",
"auth",
",",
"response",
",",
"done",
")",
"{",
"if",
"(",
"auth",
".",
"get",
"(",
"DISABLE_RETRY_REQUEST",
")",
"||",
"!",
"response",
")",
"{",
"return",
"done",
"(",
"null",
",",
"true",
")",
";",
"}",
"var",
"code",
",",
"realm",
",",
"nonce",
",",
"qop",
",",
"opaque",
",",
"authHeader",
",",
"authParams",
"=",
"{",
"}",
";",
"code",
"=",
"response",
".",
"code",
";",
"authHeader",
"=",
"_getDigestAuthHeader",
"(",
"response",
".",
"headers",
")",
";",
"// If code is forbidden or unauthorized, and an auth header exists,",
"// we can extract the realm & the nonce, and replay the request.",
"// todo: add response.is4XX, response.is5XX, etc in the SDK.",
"if",
"(",
"(",
"code",
"===",
"401",
"||",
"code",
"===",
"403",
")",
"&&",
"authHeader",
")",
"{",
"nonce",
"=",
"_extractField",
"(",
"authHeader",
".",
"value",
",",
"nonceRegex",
")",
";",
"realm",
"=",
"_extractField",
"(",
"authHeader",
".",
"value",
",",
"realmRegex",
")",
";",
"qop",
"=",
"_extractField",
"(",
"authHeader",
".",
"value",
",",
"qopRegex",
")",
";",
"opaque",
"=",
"_extractField",
"(",
"authHeader",
".",
"value",
",",
"opaqueRegex",
")",
";",
"authParams",
".",
"nonce",
"=",
"nonce",
";",
"authParams",
".",
"realm",
"=",
"realm",
";",
"opaque",
"&&",
"(",
"authParams",
".",
"opaque",
"=",
"opaque",
")",
";",
"qop",
"&&",
"(",
"authParams",
".",
"qop",
"=",
"qop",
")",
";",
"if",
"(",
"authParams",
".",
"qop",
"||",
"auth",
".",
"get",
"(",
"QOP",
")",
")",
"{",
"authParams",
".",
"clientNonce",
"=",
"randomString",
"(",
"8",
")",
";",
"authParams",
".",
"nonceCount",
"=",
"ONE",
";",
"}",
"// if all the auth parameters sent by server were already present in auth definition then we do not retry",
"if",
"(",
"_",
".",
"every",
"(",
"authParams",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"return",
"auth",
".",
"get",
"(",
"key",
")",
";",
"}",
")",
")",
"{",
"return",
"done",
"(",
"null",
",",
"true",
")",
";",
"}",
"auth",
".",
"set",
"(",
"authParams",
")",
";",
"return",
"done",
"(",
"null",
",",
"false",
")",
";",
"}",
"done",
"(",
"null",
",",
"true",
")",
";",
"}"
] |
Verifies whether the request was successfully authorized after being sent.
@param {AuthInterface} auth
@param {Response} response
@param {AuthHandlerInterface~authPostHookCallback} done
|
[
"Verifies",
"whether",
"the",
"request",
"was",
"successfully",
"authorized",
"after",
"being",
"sent",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/authorizer/digest.js#L161-L207
|
|
9,960
|
postmanlabs/postman-runtime
|
lib/authorizer/digest.js
|
function (params) {
var algorithm = params.algorithm,
username = params.username,
realm = params.realm,
password = params.password,
method = params.method,
nonce = params.nonce,
nonceCount = params.nonceCount,
clientNonce = params.clientNonce,
opaque = params.opaque,
qop = params.qop,
uri = params.uri,
// RFC defined terms, http://tools.ietf.org/html/rfc2617#section-3
A0,
A1,
A2,
hashA1,
hashA2,
reqDigest,
headerParams;
if (algorithm === MD5_SESS) {
A0 = crypto.MD5(username + COLON + realm + COLON + password).toString();
A1 = A0 + COLON + nonce + COLON + clientNonce;
}
else {
A1 = username + COLON + realm + COLON + password;
}
if (qop === AUTH_INT) {
A2 = method + COLON + uri + COLON + crypto.MD5(params.body);
}
else {
A2 = method + COLON + uri;
}
hashA1 = crypto.MD5(A1).toString();
hashA2 = crypto.MD5(A2).toString();
if (qop === AUTH || qop === AUTH_INT) {
reqDigest = crypto.MD5([hashA1, nonce, nonceCount, clientNonce, qop, hashA2].join(COLON)).toString();
}
else {
reqDigest = crypto.MD5([hashA1, nonce, hashA2].join(COLON)).toString();
}
headerParams = [USERNAME_EQUALS_QUOTE + username + QUOTE,
REALM_EQUALS_QUOTE + realm + QUOTE,
NONCE_EQUALS_QUOTE + nonce + QUOTE,
URI_EQUALS_QUOTE + uri + QUOTE
];
algorithm && headerParams.push(ALGORITHM_EQUALS_QUOTE + algorithm + QUOTE);
if (qop === AUTH || qop === AUTH_INT) {
headerParams.push(QOP_EQUALS + qop);
}
if (qop === AUTH || qop === AUTH_INT || algorithm === MD5_SESS) {
nonceCount && headerParams.push(NC_EQUALS + nonceCount);
headerParams.push(CNONCE_EQUALS_QUOTE + clientNonce + QUOTE);
}
headerParams.push(RESPONSE_EQUALS_QUOTE + reqDigest + QUOTE);
opaque && headerParams.push(OPAQUE_EQUALS_QUOTE + opaque + QUOTE);
return DIGEST_PREFIX + headerParams.join(', ');
}
|
javascript
|
function (params) {
var algorithm = params.algorithm,
username = params.username,
realm = params.realm,
password = params.password,
method = params.method,
nonce = params.nonce,
nonceCount = params.nonceCount,
clientNonce = params.clientNonce,
opaque = params.opaque,
qop = params.qop,
uri = params.uri,
// RFC defined terms, http://tools.ietf.org/html/rfc2617#section-3
A0,
A1,
A2,
hashA1,
hashA2,
reqDigest,
headerParams;
if (algorithm === MD5_SESS) {
A0 = crypto.MD5(username + COLON + realm + COLON + password).toString();
A1 = A0 + COLON + nonce + COLON + clientNonce;
}
else {
A1 = username + COLON + realm + COLON + password;
}
if (qop === AUTH_INT) {
A2 = method + COLON + uri + COLON + crypto.MD5(params.body);
}
else {
A2 = method + COLON + uri;
}
hashA1 = crypto.MD5(A1).toString();
hashA2 = crypto.MD5(A2).toString();
if (qop === AUTH || qop === AUTH_INT) {
reqDigest = crypto.MD5([hashA1, nonce, nonceCount, clientNonce, qop, hashA2].join(COLON)).toString();
}
else {
reqDigest = crypto.MD5([hashA1, nonce, hashA2].join(COLON)).toString();
}
headerParams = [USERNAME_EQUALS_QUOTE + username + QUOTE,
REALM_EQUALS_QUOTE + realm + QUOTE,
NONCE_EQUALS_QUOTE + nonce + QUOTE,
URI_EQUALS_QUOTE + uri + QUOTE
];
algorithm && headerParams.push(ALGORITHM_EQUALS_QUOTE + algorithm + QUOTE);
if (qop === AUTH || qop === AUTH_INT) {
headerParams.push(QOP_EQUALS + qop);
}
if (qop === AUTH || qop === AUTH_INT || algorithm === MD5_SESS) {
nonceCount && headerParams.push(NC_EQUALS + nonceCount);
headerParams.push(CNONCE_EQUALS_QUOTE + clientNonce + QUOTE);
}
headerParams.push(RESPONSE_EQUALS_QUOTE + reqDigest + QUOTE);
opaque && headerParams.push(OPAQUE_EQUALS_QUOTE + opaque + QUOTE);
return DIGEST_PREFIX + headerParams.join(', ');
}
|
[
"function",
"(",
"params",
")",
"{",
"var",
"algorithm",
"=",
"params",
".",
"algorithm",
",",
"username",
"=",
"params",
".",
"username",
",",
"realm",
"=",
"params",
".",
"realm",
",",
"password",
"=",
"params",
".",
"password",
",",
"method",
"=",
"params",
".",
"method",
",",
"nonce",
"=",
"params",
".",
"nonce",
",",
"nonceCount",
"=",
"params",
".",
"nonceCount",
",",
"clientNonce",
"=",
"params",
".",
"clientNonce",
",",
"opaque",
"=",
"params",
".",
"opaque",
",",
"qop",
"=",
"params",
".",
"qop",
",",
"uri",
"=",
"params",
".",
"uri",
",",
"// RFC defined terms, http://tools.ietf.org/html/rfc2617#section-3",
"A0",
",",
"A1",
",",
"A2",
",",
"hashA1",
",",
"hashA2",
",",
"reqDigest",
",",
"headerParams",
";",
"if",
"(",
"algorithm",
"===",
"MD5_SESS",
")",
"{",
"A0",
"=",
"crypto",
".",
"MD5",
"(",
"username",
"+",
"COLON",
"+",
"realm",
"+",
"COLON",
"+",
"password",
")",
".",
"toString",
"(",
")",
";",
"A1",
"=",
"A0",
"+",
"COLON",
"+",
"nonce",
"+",
"COLON",
"+",
"clientNonce",
";",
"}",
"else",
"{",
"A1",
"=",
"username",
"+",
"COLON",
"+",
"realm",
"+",
"COLON",
"+",
"password",
";",
"}",
"if",
"(",
"qop",
"===",
"AUTH_INT",
")",
"{",
"A2",
"=",
"method",
"+",
"COLON",
"+",
"uri",
"+",
"COLON",
"+",
"crypto",
".",
"MD5",
"(",
"params",
".",
"body",
")",
";",
"}",
"else",
"{",
"A2",
"=",
"method",
"+",
"COLON",
"+",
"uri",
";",
"}",
"hashA1",
"=",
"crypto",
".",
"MD5",
"(",
"A1",
")",
".",
"toString",
"(",
")",
";",
"hashA2",
"=",
"crypto",
".",
"MD5",
"(",
"A2",
")",
".",
"toString",
"(",
")",
";",
"if",
"(",
"qop",
"===",
"AUTH",
"||",
"qop",
"===",
"AUTH_INT",
")",
"{",
"reqDigest",
"=",
"crypto",
".",
"MD5",
"(",
"[",
"hashA1",
",",
"nonce",
",",
"nonceCount",
",",
"clientNonce",
",",
"qop",
",",
"hashA2",
"]",
".",
"join",
"(",
"COLON",
")",
")",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"reqDigest",
"=",
"crypto",
".",
"MD5",
"(",
"[",
"hashA1",
",",
"nonce",
",",
"hashA2",
"]",
".",
"join",
"(",
"COLON",
")",
")",
".",
"toString",
"(",
")",
";",
"}",
"headerParams",
"=",
"[",
"USERNAME_EQUALS_QUOTE",
"+",
"username",
"+",
"QUOTE",
",",
"REALM_EQUALS_QUOTE",
"+",
"realm",
"+",
"QUOTE",
",",
"NONCE_EQUALS_QUOTE",
"+",
"nonce",
"+",
"QUOTE",
",",
"URI_EQUALS_QUOTE",
"+",
"uri",
"+",
"QUOTE",
"]",
";",
"algorithm",
"&&",
"headerParams",
".",
"push",
"(",
"ALGORITHM_EQUALS_QUOTE",
"+",
"algorithm",
"+",
"QUOTE",
")",
";",
"if",
"(",
"qop",
"===",
"AUTH",
"||",
"qop",
"===",
"AUTH_INT",
")",
"{",
"headerParams",
".",
"push",
"(",
"QOP_EQUALS",
"+",
"qop",
")",
";",
"}",
"if",
"(",
"qop",
"===",
"AUTH",
"||",
"qop",
"===",
"AUTH_INT",
"||",
"algorithm",
"===",
"MD5_SESS",
")",
"{",
"nonceCount",
"&&",
"headerParams",
".",
"push",
"(",
"NC_EQUALS",
"+",
"nonceCount",
")",
";",
"headerParams",
".",
"push",
"(",
"CNONCE_EQUALS_QUOTE",
"+",
"clientNonce",
"+",
"QUOTE",
")",
";",
"}",
"headerParams",
".",
"push",
"(",
"RESPONSE_EQUALS_QUOTE",
"+",
"reqDigest",
"+",
"QUOTE",
")",
";",
"opaque",
"&&",
"headerParams",
".",
"push",
"(",
"OPAQUE_EQUALS_QUOTE",
"+",
"opaque",
"+",
"QUOTE",
")",
";",
"return",
"DIGEST_PREFIX",
"+",
"headerParams",
".",
"join",
"(",
"', '",
")",
";",
"}"
] |
Computes the Digest Authentication header from the given parameters.
@param {Object} params
@param {String} params.algorithm
@param {String} params.username
@param {String} params.realm
@param {String} params.password
@param {String} params.method
@param {String} params.nonce
@param {String} params.nonceCount
@param {String} params.clientNonce
@param {String} params.opaque
@param {String} params.qop
@param {String} params.uri
@returns {String}
|
[
"Computes",
"the",
"Digest",
"Authentication",
"header",
"from",
"the",
"given",
"parameters",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/authorizer/digest.js#L226-L294
|
|
9,961
|
postmanlabs/postman-runtime
|
lib/runner/util.js
|
function (fn, ctx) {
// extract the arguments that are to be forwarded to the function to be called
var args = Array.prototype.slice.call(arguments, 2);
try {
(typeof fn === FUNCTION) && fn.apply(ctx || global, args);
}
catch (err) {
return err;
}
}
|
javascript
|
function (fn, ctx) {
// extract the arguments that are to be forwarded to the function to be called
var args = Array.prototype.slice.call(arguments, 2);
try {
(typeof fn === FUNCTION) && fn.apply(ctx || global, args);
}
catch (err) {
return err;
}
}
|
[
"function",
"(",
"fn",
",",
"ctx",
")",
"{",
"// extract the arguments that are to be forwarded to the function to be called",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"2",
")",
";",
"try",
"{",
"(",
"typeof",
"fn",
"===",
"FUNCTION",
")",
"&&",
"fn",
".",
"apply",
"(",
"ctx",
"||",
"global",
",",
"args",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"err",
";",
"}",
"}"
] |
This function allows one to call another function by wrapping it within a try-catch block.
The first parameter is the function itself, followed by the scope in which this function is to be executed.
The third parameter onwards are blindly forwarded to the function being called
@param {Function} fn
@param {*} ctx
@returns {Error} If there was an error executing the function, the error is returned.
Note that if the function called here is asynchronous, it's errors will not be returned (for obvious reasons!)
|
[
"This",
"function",
"allows",
"one",
"to",
"call",
"another",
"function",
"by",
"wrapping",
"it",
"within",
"a",
"try",
"-",
"catch",
"block",
".",
"The",
"first",
"parameter",
"is",
"the",
"function",
"itself",
"followed",
"by",
"the",
"scope",
"in",
"which",
"this",
"function",
"is",
"to",
"be",
"executed",
".",
"The",
"third",
"parameter",
"onwards",
"are",
"blindly",
"forwarded",
"to",
"the",
"function",
"being",
"called"
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/util.js#L92-L102
|
|
9,962
|
postmanlabs/postman-runtime
|
lib/runner/util.js
|
function (dest, src) {
var prop;
// update or add values from src
for (prop in src) {
if (src.hasOwnProperty(prop)) {
dest[prop] = src[prop];
}
}
// remove values that no longer exist
for (prop in dest) {
if (dest.hasOwnProperty(prop) && !src.hasOwnProperty(prop)) {
delete dest[prop];
}
}
return dest;
}
|
javascript
|
function (dest, src) {
var prop;
// update or add values from src
for (prop in src) {
if (src.hasOwnProperty(prop)) {
dest[prop] = src[prop];
}
}
// remove values that no longer exist
for (prop in dest) {
if (dest.hasOwnProperty(prop) && !src.hasOwnProperty(prop)) {
delete dest[prop];
}
}
return dest;
}
|
[
"function",
"(",
"dest",
",",
"src",
")",
"{",
"var",
"prop",
";",
"// update or add values from src",
"for",
"(",
"prop",
"in",
"src",
")",
"{",
"if",
"(",
"src",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"dest",
"[",
"prop",
"]",
"=",
"src",
"[",
"prop",
"]",
";",
"}",
"}",
"// remove values that no longer exist",
"for",
"(",
"prop",
"in",
"dest",
")",
"{",
"if",
"(",
"dest",
".",
"hasOwnProperty",
"(",
"prop",
")",
"&&",
"!",
"src",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"delete",
"dest",
"[",
"prop",
"]",
";",
"}",
"}",
"return",
"dest",
";",
"}"
] |
Copies attributes from source object to destination object.
@param dest
@param src
@return {Object}
|
[
"Copies",
"attributes",
"from",
"source",
"object",
"to",
"destination",
"object",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/util.js#L112-L130
|
|
9,963
|
postmanlabs/postman-runtime
|
lib/runner/util.js
|
function (resolver, fileSrc, callback) {
// bail out if resolver not found.
if (!resolver) {
return callback(new Error('file resolver not supported'));
}
// bail out if resolver is not supported.
if (typeof resolver.stat !== FUNCTION || typeof resolver.createReadStream !== FUNCTION) {
return callback(new Error('file resolver interface mismatch'));
}
// bail out if file source is invalid or empty string.
if (!fileSrc || typeof fileSrc !== STRING) {
return callback(new Error('invalid or missing file source'));
}
// now that things are sanitized and validated, we transfer it to the
// stream reading utility function that does the heavy lifting of
// calling there resolver to return the stream
return createReadStream(resolver, fileSrc, callback);
}
|
javascript
|
function (resolver, fileSrc, callback) {
// bail out if resolver not found.
if (!resolver) {
return callback(new Error('file resolver not supported'));
}
// bail out if resolver is not supported.
if (typeof resolver.stat !== FUNCTION || typeof resolver.createReadStream !== FUNCTION) {
return callback(new Error('file resolver interface mismatch'));
}
// bail out if file source is invalid or empty string.
if (!fileSrc || typeof fileSrc !== STRING) {
return callback(new Error('invalid or missing file source'));
}
// now that things are sanitized and validated, we transfer it to the
// stream reading utility function that does the heavy lifting of
// calling there resolver to return the stream
return createReadStream(resolver, fileSrc, callback);
}
|
[
"function",
"(",
"resolver",
",",
"fileSrc",
",",
"callback",
")",
"{",
"// bail out if resolver not found.",
"if",
"(",
"!",
"resolver",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'file resolver not supported'",
")",
")",
";",
"}",
"// bail out if resolver is not supported.",
"if",
"(",
"typeof",
"resolver",
".",
"stat",
"!==",
"FUNCTION",
"||",
"typeof",
"resolver",
".",
"createReadStream",
"!==",
"FUNCTION",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'file resolver interface mismatch'",
")",
")",
";",
"}",
"// bail out if file source is invalid or empty string.",
"if",
"(",
"!",
"fileSrc",
"||",
"typeof",
"fileSrc",
"!==",
"STRING",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'invalid or missing file source'",
")",
")",
";",
"}",
"// now that things are sanitized and validated, we transfer it to the",
"// stream reading utility function that does the heavy lifting of",
"// calling there resolver to return the stream",
"return",
"createReadStream",
"(",
"resolver",
",",
"fileSrc",
",",
"callback",
")",
";",
"}"
] |
Create readable stream for given file as well as detect possible file
read issues. The resolver also attaches a clone function to the stream
so that the stream can be restarted any time.
@param {Object} resolver - External file resolver module
@param {Function} resolver.stat - Resolver method to check for existence and permissions of file
@param {Function} resolver.createReadStream - Resolver method for creating read stream
@param {String} fileSrc - File path
@param {Function} callback -
|
[
"Create",
"readable",
"stream",
"for",
"given",
"file",
"as",
"well",
"as",
"detect",
"possible",
"file",
"read",
"issues",
".",
"The",
"resolver",
"also",
"attaches",
"a",
"clone",
"function",
"to",
"the",
"stream",
"so",
"that",
"the",
"stream",
"can",
"be",
"restarted",
"any",
"time",
"."
] |
2d4fa9aca39ce4a3e3edecb153381fc2d59d2622
|
https://github.com/postmanlabs/postman-runtime/blob/2d4fa9aca39ce4a3e3edecb153381fc2d59d2622/lib/runner/util.js#L144-L164
|
|
9,964
|
craftzdog/react-native-sqlite-2
|
src/SQLiteDatabase.js
|
escapeForIOSAndAndroid
|
function escapeForIOSAndAndroid(args) {
if (Platform.OS === 'android' || Platform.OS === 'ios') {
return map(args, escapeBlob)
} else {
return args
}
}
|
javascript
|
function escapeForIOSAndAndroid(args) {
if (Platform.OS === 'android' || Platform.OS === 'ios') {
return map(args, escapeBlob)
} else {
return args
}
}
|
[
"function",
"escapeForIOSAndAndroid",
"(",
"args",
")",
"{",
"if",
"(",
"Platform",
".",
"OS",
"===",
"'android'",
"||",
"Platform",
".",
"OS",
"===",
"'ios'",
")",
"{",
"return",
"map",
"(",
"args",
",",
"escapeBlob",
")",
"}",
"else",
"{",
"return",
"args",
"}",
"}"
] |
for avoiding strings truncated with '\u0000'
|
[
"for",
"avoiding",
"strings",
"truncated",
"with",
"\\",
"u0000"
] |
48b2f1ce401f40b6fa42a4e3e0a1009993c3b5ac
|
https://github.com/craftzdog/react-native-sqlite-2/blob/48b2f1ce401f40b6fa42a4e3e0a1009993c3b5ac/src/SQLiteDatabase.js#L44-L50
|
9,965
|
TheBrainFamily/chimpy
|
src/lib/session-factory.js
|
SessionManagerFactory
|
function SessionManagerFactory(options) {
log.debug('[chimp][session-manager-factory] options are', options);
if (!options) {
throw new Error('options is required');
}
if (!options.port) {
throw new Error('options.port is required');
}
if (!options.browser && !options.deviceName) {
throw new Error('[chimp][session-manager-factory] options.browser or options.deviceName is required');
}
if (options.host && (options.host.indexOf('browserstack') > -1 || options.host.indexOf('saucelabs') > -1 || options.host.indexOf('testingbot') > -1)) {
if (!options.user || !options.key) {
throw new Error('[chimp][session-manager-factory] options.user and options.key are required');
}
if (options.host.indexOf('browserstack') > -1) {
return new BsManager(options);
} else if (options.host.indexOf('saucelabs') > -1) {
return new SlManager(options);
} else if (options.host.indexOf('testingbot') > -1) {
return new TbManager(options);
}
} else {
return new SessionManager(options);
}
}
|
javascript
|
function SessionManagerFactory(options) {
log.debug('[chimp][session-manager-factory] options are', options);
if (!options) {
throw new Error('options is required');
}
if (!options.port) {
throw new Error('options.port is required');
}
if (!options.browser && !options.deviceName) {
throw new Error('[chimp][session-manager-factory] options.browser or options.deviceName is required');
}
if (options.host && (options.host.indexOf('browserstack') > -1 || options.host.indexOf('saucelabs') > -1 || options.host.indexOf('testingbot') > -1)) {
if (!options.user || !options.key) {
throw new Error('[chimp][session-manager-factory] options.user and options.key are required');
}
if (options.host.indexOf('browserstack') > -1) {
return new BsManager(options);
} else if (options.host.indexOf('saucelabs') > -1) {
return new SlManager(options);
} else if (options.host.indexOf('testingbot') > -1) {
return new TbManager(options);
}
} else {
return new SessionManager(options);
}
}
|
[
"function",
"SessionManagerFactory",
"(",
"options",
")",
"{",
"log",
".",
"debug",
"(",
"'[chimp][session-manager-factory] options are'",
",",
"options",
")",
";",
"if",
"(",
"!",
"options",
")",
"{",
"throw",
"new",
"Error",
"(",
"'options is required'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"port",
")",
"{",
"throw",
"new",
"Error",
"(",
"'options.port is required'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"browser",
"&&",
"!",
"options",
".",
"deviceName",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[chimp][session-manager-factory] options.browser or options.deviceName is required'",
")",
";",
"}",
"if",
"(",
"options",
".",
"host",
"&&",
"(",
"options",
".",
"host",
".",
"indexOf",
"(",
"'browserstack'",
")",
">",
"-",
"1",
"||",
"options",
".",
"host",
".",
"indexOf",
"(",
"'saucelabs'",
")",
">",
"-",
"1",
"||",
"options",
".",
"host",
".",
"indexOf",
"(",
"'testingbot'",
")",
">",
"-",
"1",
")",
")",
"{",
"if",
"(",
"!",
"options",
".",
"user",
"||",
"!",
"options",
".",
"key",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[chimp][session-manager-factory] options.user and options.key are required'",
")",
";",
"}",
"if",
"(",
"options",
".",
"host",
".",
"indexOf",
"(",
"'browserstack'",
")",
">",
"-",
"1",
")",
"{",
"return",
"new",
"BsManager",
"(",
"options",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"host",
".",
"indexOf",
"(",
"'saucelabs'",
")",
">",
"-",
"1",
")",
"{",
"return",
"new",
"SlManager",
"(",
"options",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"host",
".",
"indexOf",
"(",
"'testingbot'",
")",
">",
"-",
"1",
")",
"{",
"return",
"new",
"TbManager",
"(",
"options",
")",
";",
"}",
"}",
"else",
"{",
"return",
"new",
"SessionManager",
"(",
"options",
")",
";",
"}",
"}"
] |
Wraps creation of different Session Managers depending on host value.
@param {Object} options
@api public
|
[
"Wraps",
"creation",
"of",
"different",
"Session",
"Managers",
"depending",
"on",
"host",
"value",
"."
] |
d859c610d247c4199945b280b0f3a14c076153c7
|
https://github.com/TheBrainFamily/chimpy/blob/d859c610d247c4199945b280b0f3a14c076153c7/src/lib/session-factory.js#L15-L49
|
9,966
|
silas/node-jenkins
|
lib/jenkins.js
|
Jenkins
|
function Jenkins(opts) {
if (!(this instanceof Jenkins)) {
return new Jenkins(opts);
}
if (typeof opts === 'string') {
opts = { baseUrl: opts };
} else {
opts = opts || {};
}
opts = Object.assign({}, opts);
if (!opts.baseUrl) {
if (opts.url) {
opts.baseUrl = opts.url;
delete opts.url;
} else {
throw new Error('baseUrl required');
}
}
if (!opts.headers) {
opts.headers = {};
}
if (!opts.headers.referer) {
opts.headers.referer = opts.baseUrl + '/';
}
if (opts.request) {
throw new Error('request not longer supported');
}
opts.name = 'jenkins';
if (typeof opts.crumbIssuer === 'function') {
this._crumbIssuer = opts.crumbIssuer;
delete opts.crumbIssuer;
} else if (opts.crumbIssuer === true) {
this._crumbIssuer = utils.crumbIssuer;
}
if (opts.formData) {
if (typeof opts.formData !== 'function' || opts.formData.name !== 'FormData') {
throw new Error('formData is invalid');
}
this._formData = opts.formData;
delete opts.formData;
}
papi.Client.call(this, opts);
this._ext('onCreate', this._onCreate);
this._ext('onResponse', this._onResponse);
this.build = new Jenkins.Build(this);
this.crumbIssuer = new Jenkins.CrumbIssuer(this);
this.job = new Jenkins.Job(this);
this.label = new Jenkins.Label(this);
this.node = new Jenkins.Node(this);
this.queue = new Jenkins.Queue(this);
this.view = new Jenkins.View(this);
try {
if (opts.promisify) {
if (typeof opts.promisify === 'function') {
papi.tools.promisify(this, opts.promisify);
} else {
papi.tools.promisify(this);
}
}
} catch (err) {
err.message = 'promisify: ' + err.message;
throw err;
}
}
|
javascript
|
function Jenkins(opts) {
if (!(this instanceof Jenkins)) {
return new Jenkins(opts);
}
if (typeof opts === 'string') {
opts = { baseUrl: opts };
} else {
opts = opts || {};
}
opts = Object.assign({}, opts);
if (!opts.baseUrl) {
if (opts.url) {
opts.baseUrl = opts.url;
delete opts.url;
} else {
throw new Error('baseUrl required');
}
}
if (!opts.headers) {
opts.headers = {};
}
if (!opts.headers.referer) {
opts.headers.referer = opts.baseUrl + '/';
}
if (opts.request) {
throw new Error('request not longer supported');
}
opts.name = 'jenkins';
if (typeof opts.crumbIssuer === 'function') {
this._crumbIssuer = opts.crumbIssuer;
delete opts.crumbIssuer;
} else if (opts.crumbIssuer === true) {
this._crumbIssuer = utils.crumbIssuer;
}
if (opts.formData) {
if (typeof opts.formData !== 'function' || opts.formData.name !== 'FormData') {
throw new Error('formData is invalid');
}
this._formData = opts.formData;
delete opts.formData;
}
papi.Client.call(this, opts);
this._ext('onCreate', this._onCreate);
this._ext('onResponse', this._onResponse);
this.build = new Jenkins.Build(this);
this.crumbIssuer = new Jenkins.CrumbIssuer(this);
this.job = new Jenkins.Job(this);
this.label = new Jenkins.Label(this);
this.node = new Jenkins.Node(this);
this.queue = new Jenkins.Queue(this);
this.view = new Jenkins.View(this);
try {
if (opts.promisify) {
if (typeof opts.promisify === 'function') {
papi.tools.promisify(this, opts.promisify);
} else {
papi.tools.promisify(this);
}
}
} catch (err) {
err.message = 'promisify: ' + err.message;
throw err;
}
}
|
[
"function",
"Jenkins",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Jenkins",
")",
")",
"{",
"return",
"new",
"Jenkins",
"(",
"opts",
")",
";",
"}",
"if",
"(",
"typeof",
"opts",
"===",
"'string'",
")",
"{",
"opts",
"=",
"{",
"baseUrl",
":",
"opts",
"}",
";",
"}",
"else",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"}",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
")",
";",
"if",
"(",
"!",
"opts",
".",
"baseUrl",
")",
"{",
"if",
"(",
"opts",
".",
"url",
")",
"{",
"opts",
".",
"baseUrl",
"=",
"opts",
".",
"url",
";",
"delete",
"opts",
".",
"url",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'baseUrl required'",
")",
";",
"}",
"}",
"if",
"(",
"!",
"opts",
".",
"headers",
")",
"{",
"opts",
".",
"headers",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"opts",
".",
"headers",
".",
"referer",
")",
"{",
"opts",
".",
"headers",
".",
"referer",
"=",
"opts",
".",
"baseUrl",
"+",
"'/'",
";",
"}",
"if",
"(",
"opts",
".",
"request",
")",
"{",
"throw",
"new",
"Error",
"(",
"'request not longer supported'",
")",
";",
"}",
"opts",
".",
"name",
"=",
"'jenkins'",
";",
"if",
"(",
"typeof",
"opts",
".",
"crumbIssuer",
"===",
"'function'",
")",
"{",
"this",
".",
"_crumbIssuer",
"=",
"opts",
".",
"crumbIssuer",
";",
"delete",
"opts",
".",
"crumbIssuer",
";",
"}",
"else",
"if",
"(",
"opts",
".",
"crumbIssuer",
"===",
"true",
")",
"{",
"this",
".",
"_crumbIssuer",
"=",
"utils",
".",
"crumbIssuer",
";",
"}",
"if",
"(",
"opts",
".",
"formData",
")",
"{",
"if",
"(",
"typeof",
"opts",
".",
"formData",
"!==",
"'function'",
"||",
"opts",
".",
"formData",
".",
"name",
"!==",
"'FormData'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'formData is invalid'",
")",
";",
"}",
"this",
".",
"_formData",
"=",
"opts",
".",
"formData",
";",
"delete",
"opts",
".",
"formData",
";",
"}",
"papi",
".",
"Client",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"this",
".",
"_ext",
"(",
"'onCreate'",
",",
"this",
".",
"_onCreate",
")",
";",
"this",
".",
"_ext",
"(",
"'onResponse'",
",",
"this",
".",
"_onResponse",
")",
";",
"this",
".",
"build",
"=",
"new",
"Jenkins",
".",
"Build",
"(",
"this",
")",
";",
"this",
".",
"crumbIssuer",
"=",
"new",
"Jenkins",
".",
"CrumbIssuer",
"(",
"this",
")",
";",
"this",
".",
"job",
"=",
"new",
"Jenkins",
".",
"Job",
"(",
"this",
")",
";",
"this",
".",
"label",
"=",
"new",
"Jenkins",
".",
"Label",
"(",
"this",
")",
";",
"this",
".",
"node",
"=",
"new",
"Jenkins",
".",
"Node",
"(",
"this",
")",
";",
"this",
".",
"queue",
"=",
"new",
"Jenkins",
".",
"Queue",
"(",
"this",
")",
";",
"this",
".",
"view",
"=",
"new",
"Jenkins",
".",
"View",
"(",
"this",
")",
";",
"try",
"{",
"if",
"(",
"opts",
".",
"promisify",
")",
"{",
"if",
"(",
"typeof",
"opts",
".",
"promisify",
"===",
"'function'",
")",
"{",
"papi",
".",
"tools",
".",
"promisify",
"(",
"this",
",",
"opts",
".",
"promisify",
")",
";",
"}",
"else",
"{",
"papi",
".",
"tools",
".",
"promisify",
"(",
"this",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"err",
".",
"message",
"=",
"'promisify: '",
"+",
"err",
".",
"message",
";",
"throw",
"err",
";",
"}",
"}"
] |
Initialize a new `Jenkins` client.
|
[
"Initialize",
"a",
"new",
"Jenkins",
"client",
"."
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/jenkins.js#L28-L103
|
9,967
|
silas/node-jenkins
|
lib/middleware.js
|
ignoreErrorForStatusCodes
|
function ignoreErrorForStatusCodes() {
var statusCodes = Array.prototype.slice.call(arguments);
return function(ctx, next) {
if (ctx.err && ctx.res && statusCodes.indexOf(ctx.res.statusCode) !== -1) {
delete ctx.err;
}
next();
};
}
|
javascript
|
function ignoreErrorForStatusCodes() {
var statusCodes = Array.prototype.slice.call(arguments);
return function(ctx, next) {
if (ctx.err && ctx.res && statusCodes.indexOf(ctx.res.statusCode) !== -1) {
delete ctx.err;
}
next();
};
}
|
[
"function",
"ignoreErrorForStatusCodes",
"(",
")",
"{",
"var",
"statusCodes",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"return",
"function",
"(",
"ctx",
",",
"next",
")",
"{",
"if",
"(",
"ctx",
".",
"err",
"&&",
"ctx",
".",
"res",
"&&",
"statusCodes",
".",
"indexOf",
"(",
"ctx",
".",
"res",
".",
"statusCode",
")",
"!==",
"-",
"1",
")",
"{",
"delete",
"ctx",
".",
"err",
";",
"}",
"next",
"(",
")",
";",
"}",
";",
"}"
] |
Ignore errors for provided status codes
|
[
"Ignore",
"errors",
"for",
"provided",
"status",
"codes"
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/middleware.js#L57-L67
|
9,968
|
silas/node-jenkins
|
lib/middleware.js
|
require302
|
function require302(message) {
return function(ctx, next) {
if (ctx.res && ctx.res.statusCode === 302) {
return next(false);
} else if (ctx.res) {
if (ctx.err) {
if (!ctx.res.headers['x-error']) ctx.err.message = message;
} else {
ctx.err = new Error(message);
}
return next(ctx.err);
}
next();
};
}
|
javascript
|
function require302(message) {
return function(ctx, next) {
if (ctx.res && ctx.res.statusCode === 302) {
return next(false);
} else if (ctx.res) {
if (ctx.err) {
if (!ctx.res.headers['x-error']) ctx.err.message = message;
} else {
ctx.err = new Error(message);
}
return next(ctx.err);
}
next();
};
}
|
[
"function",
"require302",
"(",
"message",
")",
"{",
"return",
"function",
"(",
"ctx",
",",
"next",
")",
"{",
"if",
"(",
"ctx",
".",
"res",
"&&",
"ctx",
".",
"res",
".",
"statusCode",
"===",
"302",
")",
"{",
"return",
"next",
"(",
"false",
")",
";",
"}",
"else",
"if",
"(",
"ctx",
".",
"res",
")",
"{",
"if",
"(",
"ctx",
".",
"err",
")",
"{",
"if",
"(",
"!",
"ctx",
".",
"res",
".",
"headers",
"[",
"'x-error'",
"]",
")",
"ctx",
".",
"err",
".",
"message",
"=",
"message",
";",
"}",
"else",
"{",
"ctx",
".",
"err",
"=",
"new",
"Error",
"(",
"message",
")",
";",
"}",
"return",
"next",
"(",
"ctx",
".",
"err",
")",
";",
"}",
"next",
"(",
")",
";",
"}",
";",
"}"
] |
Require 302 or error
|
[
"Require",
"302",
"or",
"error"
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/middleware.js#L73-L89
|
9,969
|
silas/node-jenkins
|
lib/utils.js
|
parseName
|
function parseName(value) {
var jobParts = [];
var pathParts = (urlParse(value).pathname || '').split('/').filter(Boolean);
var state = 0;
var part;
// iterate until we find our first job, then collect the continuous job parts
// ['foo', 'job', 'a', 'job', 'b', 'bar', 'job', 'c'] => ['a', 'b']
loop:
for (var i = 0; i < pathParts.length; i++) {
part = pathParts[i];
switch (state) {
case 0:
if (part === 'job') state = 2;
break;
case 1:
if (part !== 'job') break loop;
state = 2;
break;
case 2:
jobParts.push(part);
state = 1;
break;
}
}
return jobParts.map(decodeURIComponent);
}
|
javascript
|
function parseName(value) {
var jobParts = [];
var pathParts = (urlParse(value).pathname || '').split('/').filter(Boolean);
var state = 0;
var part;
// iterate until we find our first job, then collect the continuous job parts
// ['foo', 'job', 'a', 'job', 'b', 'bar', 'job', 'c'] => ['a', 'b']
loop:
for (var i = 0; i < pathParts.length; i++) {
part = pathParts[i];
switch (state) {
case 0:
if (part === 'job') state = 2;
break;
case 1:
if (part !== 'job') break loop;
state = 2;
break;
case 2:
jobParts.push(part);
state = 1;
break;
}
}
return jobParts.map(decodeURIComponent);
}
|
[
"function",
"parseName",
"(",
"value",
")",
"{",
"var",
"jobParts",
"=",
"[",
"]",
";",
"var",
"pathParts",
"=",
"(",
"urlParse",
"(",
"value",
")",
".",
"pathname",
"||",
"''",
")",
".",
"split",
"(",
"'/'",
")",
".",
"filter",
"(",
"Boolean",
")",
";",
"var",
"state",
"=",
"0",
";",
"var",
"part",
";",
"// iterate until we find our first job, then collect the continuous job parts",
"// ['foo', 'job', 'a', 'job', 'b', 'bar', 'job', 'c'] => ['a', 'b']",
"loop",
":",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"pathParts",
".",
"length",
";",
"i",
"++",
")",
"{",
"part",
"=",
"pathParts",
"[",
"i",
"]",
";",
"switch",
"(",
"state",
")",
"{",
"case",
"0",
":",
"if",
"(",
"part",
"===",
"'job'",
")",
"state",
"=",
"2",
";",
"break",
";",
"case",
"1",
":",
"if",
"(",
"part",
"!==",
"'job'",
")",
"break",
"loop",
";",
"state",
"=",
"2",
";",
"break",
";",
"case",
"2",
":",
"jobParts",
".",
"push",
"(",
"part",
")",
";",
"state",
"=",
"1",
";",
"break",
";",
"}",
"}",
"return",
"jobParts",
".",
"map",
"(",
"decodeURIComponent",
")",
";",
"}"
] |
Parse job name from URL
|
[
"Parse",
"job",
"name",
"from",
"URL"
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/utils.js#L48-L77
|
9,970
|
silas/node-jenkins
|
lib/utils.js
|
FolderPath
|
function FolderPath(value) {
if (!(this instanceof FolderPath)) {
return new FolderPath(value);
}
if (Array.isArray(value)) {
this.value = value;
} else if (typeof value === 'string') {
if (value.match('^https?:\/\/')) {
this.value = parseName(value);
} else {
this.value = value.split('/').filter(Boolean);
}
} else {
this.value = [];
}
}
|
javascript
|
function FolderPath(value) {
if (!(this instanceof FolderPath)) {
return new FolderPath(value);
}
if (Array.isArray(value)) {
this.value = value;
} else if (typeof value === 'string') {
if (value.match('^https?:\/\/')) {
this.value = parseName(value);
} else {
this.value = value.split('/').filter(Boolean);
}
} else {
this.value = [];
}
}
|
[
"function",
"FolderPath",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"FolderPath",
")",
")",
"{",
"return",
"new",
"FolderPath",
"(",
"value",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"this",
".",
"value",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
")",
"{",
"if",
"(",
"value",
".",
"match",
"(",
"'^https?:\\/\\/'",
")",
")",
"{",
"this",
".",
"value",
"=",
"parseName",
"(",
"value",
")",
";",
"}",
"else",
"{",
"this",
".",
"value",
"=",
"value",
".",
"split",
"(",
"'/'",
")",
".",
"filter",
"(",
"Boolean",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"value",
"=",
"[",
"]",
";",
"}",
"}"
] |
Path for folder plugin
|
[
"Path",
"for",
"folder",
"plugin"
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/utils.js#L83-L98
|
9,971
|
silas/node-jenkins
|
lib/utils.js
|
crumbIssuer
|
function crumbIssuer(jenkins, callback) {
jenkins.crumbIssuer.get(function(err, data) {
if (err) return callback(err);
if (!data || !data.crumbRequestField || !data.crumb) {
return callback(new Error('Failed to get crumb'));
}
callback(null, {
headerName: data.crumbRequestField,
headerValue: data.crumb,
});
});
}
|
javascript
|
function crumbIssuer(jenkins, callback) {
jenkins.crumbIssuer.get(function(err, data) {
if (err) return callback(err);
if (!data || !data.crumbRequestField || !data.crumb) {
return callback(new Error('Failed to get crumb'));
}
callback(null, {
headerName: data.crumbRequestField,
headerValue: data.crumb,
});
});
}
|
[
"function",
"crumbIssuer",
"(",
"jenkins",
",",
"callback",
")",
"{",
"jenkins",
".",
"crumbIssuer",
".",
"get",
"(",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"if",
"(",
"!",
"data",
"||",
"!",
"data",
".",
"crumbRequestField",
"||",
"!",
"data",
".",
"crumb",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Failed to get crumb'",
")",
")",
";",
"}",
"callback",
"(",
"null",
",",
"{",
"headerName",
":",
"data",
".",
"crumbRequestField",
",",
"headerValue",
":",
"data",
".",
"crumb",
",",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Default crumb issuser
|
[
"Default",
"crumb",
"issuser"
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/utils.js#L127-L139
|
9,972
|
silas/node-jenkins
|
lib/utils.js
|
isFileLike
|
function isFileLike(v) {
return Buffer.isBuffer(v) ||
typeof v === 'object' &&
typeof v.pipe === 'function' &&
v.readable !== false;
}
|
javascript
|
function isFileLike(v) {
return Buffer.isBuffer(v) ||
typeof v === 'object' &&
typeof v.pipe === 'function' &&
v.readable !== false;
}
|
[
"function",
"isFileLike",
"(",
"v",
")",
"{",
"return",
"Buffer",
".",
"isBuffer",
"(",
"v",
")",
"||",
"typeof",
"v",
"===",
"'object'",
"&&",
"typeof",
"v",
".",
"pipe",
"===",
"'function'",
"&&",
"v",
".",
"readable",
"!==",
"false",
";",
"}"
] |
Check if object is file like
|
[
"Check",
"if",
"object",
"is",
"file",
"like"
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/utils.js#L145-L150
|
9,973
|
silas/node-jenkins
|
lib/log_stream.js
|
LogStream
|
function LogStream(jenkins, opts) {
var self = this;
events.EventEmitter.call(self);
self._jenkins = jenkins;
opts = opts || {};
self._delay = opts.delay || 1000;
delete opts.delay;
self._opts = {};
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
self._opts[key] = opts[key];
}
}
self._opts.meta = true;
process.nextTick(function() { self._run(); });
}
|
javascript
|
function LogStream(jenkins, opts) {
var self = this;
events.EventEmitter.call(self);
self._jenkins = jenkins;
opts = opts || {};
self._delay = opts.delay || 1000;
delete opts.delay;
self._opts = {};
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
self._opts[key] = opts[key];
}
}
self._opts.meta = true;
process.nextTick(function() { self._run(); });
}
|
[
"function",
"LogStream",
"(",
"jenkins",
",",
"opts",
")",
"{",
"var",
"self",
"=",
"this",
";",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"self",
")",
";",
"self",
".",
"_jenkins",
"=",
"jenkins",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"self",
".",
"_delay",
"=",
"opts",
".",
"delay",
"||",
"1000",
";",
"delete",
"opts",
".",
"delay",
";",
"self",
".",
"_opts",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"opts",
")",
"{",
"if",
"(",
"opts",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"self",
".",
"_opts",
"[",
"key",
"]",
"=",
"opts",
"[",
"key",
"]",
";",
"}",
"}",
"self",
".",
"_opts",
".",
"meta",
"=",
"true",
";",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"self",
".",
"_run",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Initialize a new `LogStream` instance.
|
[
"Initialize",
"a",
"new",
"LogStream",
"instance",
"."
] |
d734afcf2469e3dbe262f1036d1061b52894151f
|
https://github.com/silas/node-jenkins/blob/d734afcf2469e3dbe262f1036d1061b52894151f/lib/log_stream.js#L18-L39
|
9,974
|
JamesBarwell/rpi-gpio.js
|
rpi-gpio.js
|
setRaspberryVersion
|
function setRaspberryVersion() {
if (currentPins) {
return Promise.resolve();
}
return new Promise(function(resolve, reject) {
fs.readFile('/proc/cpuinfo', 'utf8', function(err, data) {
if (err) {
return reject(err);
}
// Match the last 4 digits of the number following "Revision:"
var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
if (!match) {
var errorMessage = 'Unable to match Revision in /proc/cpuinfo: ' + data;
return reject(new Error(errorMessage));
}
var revisionNumber = parseInt(match[1], 16);
var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';
debug(
'seen hardware revision %d; using pin mode %s',
revisionNumber,
pinVersion
);
// Create a list of valid BCM pins for this Raspberry Pi version.
// This will be used to validate channel numbers in getPinBcm
currentValidBcmPins = []
Object.keys(PINS[pinVersion]).forEach(
function(pin) {
// Lookup the BCM pin for the RPI pin and add it to the list
currentValidBcmPins.push(PINS[pinVersion][pin]);
}
);
currentPins = PINS[pinVersion];
return resolve();
});
});
}
|
javascript
|
function setRaspberryVersion() {
if (currentPins) {
return Promise.resolve();
}
return new Promise(function(resolve, reject) {
fs.readFile('/proc/cpuinfo', 'utf8', function(err, data) {
if (err) {
return reject(err);
}
// Match the last 4 digits of the number following "Revision:"
var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
if (!match) {
var errorMessage = 'Unable to match Revision in /proc/cpuinfo: ' + data;
return reject(new Error(errorMessage));
}
var revisionNumber = parseInt(match[1], 16);
var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';
debug(
'seen hardware revision %d; using pin mode %s',
revisionNumber,
pinVersion
);
// Create a list of valid BCM pins for this Raspberry Pi version.
// This will be used to validate channel numbers in getPinBcm
currentValidBcmPins = []
Object.keys(PINS[pinVersion]).forEach(
function(pin) {
// Lookup the BCM pin for the RPI pin and add it to the list
currentValidBcmPins.push(PINS[pinVersion][pin]);
}
);
currentPins = PINS[pinVersion];
return resolve();
});
});
}
|
[
"function",
"setRaspberryVersion",
"(",
")",
"{",
"if",
"(",
"currentPins",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"fs",
".",
"readFile",
"(",
"'/proc/cpuinfo'",
",",
"'utf8'",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"// Match the last 4 digits of the number following \"Revision:\"",
"var",
"match",
"=",
"data",
".",
"match",
"(",
"/",
"Revision\\s*:\\s*[0-9a-f]*([0-9a-f]{4})",
"/",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"var",
"errorMessage",
"=",
"'Unable to match Revision in /proc/cpuinfo: '",
"+",
"data",
";",
"return",
"reject",
"(",
"new",
"Error",
"(",
"errorMessage",
")",
")",
";",
"}",
"var",
"revisionNumber",
"=",
"parseInt",
"(",
"match",
"[",
"1",
"]",
",",
"16",
")",
";",
"var",
"pinVersion",
"=",
"(",
"revisionNumber",
"<",
"4",
")",
"?",
"'v1'",
":",
"'v2'",
";",
"debug",
"(",
"'seen hardware revision %d; using pin mode %s'",
",",
"revisionNumber",
",",
"pinVersion",
")",
";",
"// Create a list of valid BCM pins for this Raspberry Pi version.",
"// This will be used to validate channel numbers in getPinBcm",
"currentValidBcmPins",
"=",
"[",
"]",
"Object",
".",
"keys",
"(",
"PINS",
"[",
"pinVersion",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"pin",
")",
"{",
"// Lookup the BCM pin for the RPI pin and add it to the list",
"currentValidBcmPins",
".",
"push",
"(",
"PINS",
"[",
"pinVersion",
"]",
"[",
"pin",
"]",
")",
";",
"}",
")",
";",
"currentPins",
"=",
"PINS",
"[",
"pinVersion",
"]",
";",
"return",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Private functions requring access to state
|
[
"Private",
"functions",
"requring",
"access",
"to",
"state"
] |
8cdbec5a7fb6dd1ee095e9f9109adda19372da3b
|
https://github.com/JamesBarwell/rpi-gpio.js/blob/8cdbec5a7fb6dd1ee095e9f9109adda19372da3b/rpi-gpio.js#L353-L396
|
9,975
|
JamesBarwell/rpi-gpio.js
|
rpi-gpio.js
|
listen
|
function listen(channel, onChange) {
var pin = getPinForCurrentMode(channel);
if (!exportedInputPins[pin] && !exportedOutputPins[pin]) {
throw new Error('Channel %d has not been exported', channel);
}
debug('listen for pin %d', pin);
var poller = new Epoll(function(err, innerfd, events) {
if (err) throw err
clearInterrupt(innerfd);
onChange(channel);
});
var fd = fs.openSync(PATH + '/gpio' + pin + '/value', 'r+');
clearInterrupt(fd);
poller.add(fd, Epoll.EPOLLPRI);
// Append ready-to-use remove function
pollers[pin] = function() {
poller.remove(fd).close();
}
}
|
javascript
|
function listen(channel, onChange) {
var pin = getPinForCurrentMode(channel);
if (!exportedInputPins[pin] && !exportedOutputPins[pin]) {
throw new Error('Channel %d has not been exported', channel);
}
debug('listen for pin %d', pin);
var poller = new Epoll(function(err, innerfd, events) {
if (err) throw err
clearInterrupt(innerfd);
onChange(channel);
});
var fd = fs.openSync(PATH + '/gpio' + pin + '/value', 'r+');
clearInterrupt(fd);
poller.add(fd, Epoll.EPOLLPRI);
// Append ready-to-use remove function
pollers[pin] = function() {
poller.remove(fd).close();
}
}
|
[
"function",
"listen",
"(",
"channel",
",",
"onChange",
")",
"{",
"var",
"pin",
"=",
"getPinForCurrentMode",
"(",
"channel",
")",
";",
"if",
"(",
"!",
"exportedInputPins",
"[",
"pin",
"]",
"&&",
"!",
"exportedOutputPins",
"[",
"pin",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Channel %d has not been exported'",
",",
"channel",
")",
";",
"}",
"debug",
"(",
"'listen for pin %d'",
",",
"pin",
")",
";",
"var",
"poller",
"=",
"new",
"Epoll",
"(",
"function",
"(",
"err",
",",
"innerfd",
",",
"events",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
"clearInterrupt",
"(",
"innerfd",
")",
";",
"onChange",
"(",
"channel",
")",
";",
"}",
")",
";",
"var",
"fd",
"=",
"fs",
".",
"openSync",
"(",
"PATH",
"+",
"'/gpio'",
"+",
"pin",
"+",
"'/value'",
",",
"'r+'",
")",
";",
"clearInterrupt",
"(",
"fd",
")",
";",
"poller",
".",
"add",
"(",
"fd",
",",
"Epoll",
".",
"EPOLLPRI",
")",
";",
"// Append ready-to-use remove function",
"pollers",
"[",
"pin",
"]",
"=",
"function",
"(",
")",
"{",
"poller",
".",
"remove",
"(",
"fd",
")",
".",
"close",
"(",
")",
";",
"}",
"}"
] |
Listen for interrupts on a channel
@param {number} channel The channel to watch
@param {function} cb Callback which receives the channel's err
|
[
"Listen",
"for",
"interrupts",
"on",
"a",
"channel"
] |
8cdbec5a7fb6dd1ee095e9f9109adda19372da3b
|
https://github.com/JamesBarwell/rpi-gpio.js/blob/8cdbec5a7fb6dd1ee095e9f9109adda19372da3b/rpi-gpio.js#L413-L434
|
9,976
|
treasure-data/td-js-sdk
|
lib/utils/toBase64.js
|
encode
|
function encode (n) {
var o = ''
var i = 0
var i1, i2, i3, e1, e2, e3, e4
n = utf8Encode(n)
while (i < n.length) {
i1 = n.charCodeAt(i++)
i2 = n.charCodeAt(i++)
i3 = n.charCodeAt(i++)
e1 = (i1 >> 2)
e2 = (((i1 & 3) << 4) | (i2 >> 4))
e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6))
e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63
o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4)
}
return o
}
|
javascript
|
function encode (n) {
var o = ''
var i = 0
var i1, i2, i3, e1, e2, e3, e4
n = utf8Encode(n)
while (i < n.length) {
i1 = n.charCodeAt(i++)
i2 = n.charCodeAt(i++)
i3 = n.charCodeAt(i++)
e1 = (i1 >> 2)
e2 = (((i1 & 3) << 4) | (i2 >> 4))
e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6))
e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63
o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4)
}
return o
}
|
[
"function",
"encode",
"(",
"n",
")",
"{",
"var",
"o",
"=",
"''",
"var",
"i",
"=",
"0",
"var",
"i1",
",",
"i2",
",",
"i3",
",",
"e1",
",",
"e2",
",",
"e3",
",",
"e4",
"n",
"=",
"utf8Encode",
"(",
"n",
")",
"while",
"(",
"i",
"<",
"n",
".",
"length",
")",
"{",
"i1",
"=",
"n",
".",
"charCodeAt",
"(",
"i",
"++",
")",
"i2",
"=",
"n",
".",
"charCodeAt",
"(",
"i",
"++",
")",
"i3",
"=",
"n",
".",
"charCodeAt",
"(",
"i",
"++",
")",
"e1",
"=",
"(",
"i1",
">>",
"2",
")",
"e2",
"=",
"(",
"(",
"(",
"i1",
"&",
"3",
")",
"<<",
"4",
")",
"|",
"(",
"i2",
">>",
"4",
")",
")",
"e3",
"=",
"(",
"isNaN",
"(",
"i2",
")",
"?",
"64",
":",
"(",
"(",
"i2",
"&",
"15",
")",
"<<",
"2",
")",
"|",
"(",
"i3",
">>",
"6",
")",
")",
"e4",
"=",
"(",
"isNaN",
"(",
"i2",
")",
"||",
"isNaN",
"(",
"i3",
")",
")",
"?",
"64",
":",
"i3",
"&",
"63",
"o",
"=",
"o",
"+",
"m",
".",
"charAt",
"(",
"e1",
")",
"+",
"m",
".",
"charAt",
"(",
"e2",
")",
"+",
"m",
".",
"charAt",
"(",
"e3",
")",
"+",
"m",
".",
"charAt",
"(",
"e4",
")",
"}",
"return",
"o",
"}"
] |
base64 encode a string
@param {string} n
@return {string}
|
[
"base64",
"encode",
"a",
"string"
] |
dc817573ba487388845170f915ffeceaa24cc887
|
https://github.com/treasure-data/td-js-sdk/blob/dc817573ba487388845170f915ffeceaa24cc887/lib/utils/toBase64.js#L12-L28
|
9,977
|
treasure-data/td-js-sdk
|
lib/record.js
|
validateRecord
|
function validateRecord (table, record) {
invariant(
_.isString(table),
'Must provide a table'
)
invariant(
/^[a-z0-9_]{3,255}$/.test(table),
'Table must be between 3 and 255 characters and must ' +
'consist only of lower case letters, numbers, and _'
)
invariant(
_.isObject(record),
'Must provide a record'
)
}
|
javascript
|
function validateRecord (table, record) {
invariant(
_.isString(table),
'Must provide a table'
)
invariant(
/^[a-z0-9_]{3,255}$/.test(table),
'Table must be between 3 and 255 characters and must ' +
'consist only of lower case letters, numbers, and _'
)
invariant(
_.isObject(record),
'Must provide a record'
)
}
|
[
"function",
"validateRecord",
"(",
"table",
",",
"record",
")",
"{",
"invariant",
"(",
"_",
".",
"isString",
"(",
"table",
")",
",",
"'Must provide a table'",
")",
"invariant",
"(",
"/",
"^[a-z0-9_]{3,255}$",
"/",
".",
"test",
"(",
"table",
")",
",",
"'Table must be between 3 and 255 characters and must '",
"+",
"'consist only of lower case letters, numbers, and _'",
")",
"invariant",
"(",
"_",
".",
"isObject",
"(",
"record",
")",
",",
"'Must provide a record'",
")",
"}"
] |
Helpers
Validate record
|
[
"Helpers",
"Validate",
"record"
] |
dc817573ba487388845170f915ffeceaa24cc887
|
https://github.com/treasure-data/td-js-sdk/blob/dc817573ba487388845170f915ffeceaa24cc887/lib/record.js#L20-L36
|
9,978
|
Jam3/preloader
|
lib/loaders/FileMeta.js
|
function (header) {
/**
* This property is the mimetype for the file
*
* @property mime
* @type {String}
*/
this.mime = null;
/**
* This is the file size in bytes
*
* @type {Number}
*/
this.size = null;
/**
* This is a Date object which represents the last time this file was modified
*
* @type {Date}
*/
this.lastModified = null;
/**
* This is the HTTP header as an Object for the file.
*
* @type {Object}
*/
this.httpHeader = null;
if (header) this.setFromHTTPHeader(header);
}
|
javascript
|
function (header) {
/**
* This property is the mimetype for the file
*
* @property mime
* @type {String}
*/
this.mime = null;
/**
* This is the file size in bytes
*
* @type {Number}
*/
this.size = null;
/**
* This is a Date object which represents the last time this file was modified
*
* @type {Date}
*/
this.lastModified = null;
/**
* This is the HTTP header as an Object for the file.
*
* @type {Object}
*/
this.httpHeader = null;
if (header) this.setFromHTTPHeader(header);
}
|
[
"function",
"(",
"header",
")",
"{",
"/**\n * This property is the mimetype for the file\n *\n * @property mime\n * @type {String}\n */",
"this",
".",
"mime",
"=",
"null",
";",
"/**\n * This is the file size in bytes\n *\n * @type {Number}\n */",
"this",
".",
"size",
"=",
"null",
";",
"/**\n * This is a Date object which represents the last time this file was modified\n *\n * @type {Date}\n */",
"this",
".",
"lastModified",
"=",
"null",
";",
"/**\n * This is the HTTP header as an Object for the file.\n *\n * @type {Object}\n */",
"this",
".",
"httpHeader",
"=",
"null",
";",
"if",
"(",
"header",
")",
"this",
".",
"setFromHTTPHeader",
"(",
"header",
")",
";",
"}"
] |
FileMeta is a class which will hold file meta data. Each LoaderBase contains a FileMeta object
that you can use to query.
@class FileMeta
@constructor
@param {String} header HTTP Header sent when loading this file
|
[
"FileMeta",
"is",
"a",
"class",
"which",
"will",
"hold",
"file",
"meta",
"data",
".",
"Each",
"LoaderBase",
"contains",
"a",
"FileMeta",
"object",
"that",
"you",
"can",
"use",
"to",
"query",
"."
] |
f094e19a423245f50def5fa37b3702d5eb4852ea
|
https://github.com/Jam3/preloader/blob/f094e19a423245f50def5fa37b3702d5eb4852ea/lib/loaders/FileMeta.js#L11-L42
|
|
9,979
|
Jam3/preloader
|
lib/loaders/FileMeta.js
|
function (header) {
this.httpHeader = parseHTTPHeader(header);
if (this.httpHeader[ 'content-length' ]) this.size = this.httpHeader[ 'content-length' ];
if (this.httpHeader[ 'content-type' ]) this.mime = this.httpHeader[ 'content-type' ];
if (this.httpHeader[ 'last-modified' ]) this.lastModified = new Date(this.httpHeader[ 'last-modified' ]);
}
|
javascript
|
function (header) {
this.httpHeader = parseHTTPHeader(header);
if (this.httpHeader[ 'content-length' ]) this.size = this.httpHeader[ 'content-length' ];
if (this.httpHeader[ 'content-type' ]) this.mime = this.httpHeader[ 'content-type' ];
if (this.httpHeader[ 'last-modified' ]) this.lastModified = new Date(this.httpHeader[ 'last-modified' ]);
}
|
[
"function",
"(",
"header",
")",
"{",
"this",
".",
"httpHeader",
"=",
"parseHTTPHeader",
"(",
"header",
")",
";",
"if",
"(",
"this",
".",
"httpHeader",
"[",
"'content-length'",
"]",
")",
"this",
".",
"size",
"=",
"this",
".",
"httpHeader",
"[",
"'content-length'",
"]",
";",
"if",
"(",
"this",
".",
"httpHeader",
"[",
"'content-type'",
"]",
")",
"this",
".",
"mime",
"=",
"this",
".",
"httpHeader",
"[",
"'content-type'",
"]",
";",
"if",
"(",
"this",
".",
"httpHeader",
"[",
"'last-modified'",
"]",
")",
"this",
".",
"lastModified",
"=",
"new",
"Date",
"(",
"this",
".",
"httpHeader",
"[",
"'last-modified'",
"]",
")",
";",
"}"
] |
This function will be called in the constructor of FileMeta. It will parse the HTTP
headers returned by a server and save useful information for development.
@method setFromHTTPHeader
@param {String} header HTTP header returned by the server
|
[
"This",
"function",
"will",
"be",
"called",
"in",
"the",
"constructor",
"of",
"FileMeta",
".",
"It",
"will",
"parse",
"the",
"HTTP",
"headers",
"returned",
"by",
"a",
"server",
"and",
"save",
"useful",
"information",
"for",
"development",
"."
] |
f094e19a423245f50def5fa37b3702d5eb4852ea
|
https://github.com/Jam3/preloader/blob/f094e19a423245f50def5fa37b3702d5eb4852ea/lib/loaders/FileMeta.js#L53-L61
|
|
9,980
|
Jam3/preloader
|
lib/loaders/LoaderBase.js
|
function (url) {
this.url = url;
if (this.canLoadUsingXHR()) {
this.xhr = new XMLHttpRequest();
this.xhr.open('GET', url, true);
this.xhr.onreadystatechange = this._onStateChange;
this.xhr.onprogress !== undefined && (this.xhr.onprogress = this._onProgress);
if (this.loadType !== LoaderBase.typeText) {
if (!checkIfGoodValue.call(this)) {
console.warn('Attempting to use incompatible load type ' + this.loadType + '. Switching it to ' + LoaderBase.typeText);
this.loadType = LoaderBase.typeText;
}
try {
this.loadTypeSet = checkResponseTypeSupport.call(this) && checkAndSetType(this.xhr, this.loadType);
} catch (e) {
this.loadTypeSet = false;
}
if (!this.loadTypeSet && (this.loadType === LoaderBase.typeBlob || this.loadType === LoaderBase.typeArraybuffer)) {
this.xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
}
this.xhr.send();
}
}
|
javascript
|
function (url) {
this.url = url;
if (this.canLoadUsingXHR()) {
this.xhr = new XMLHttpRequest();
this.xhr.open('GET', url, true);
this.xhr.onreadystatechange = this._onStateChange;
this.xhr.onprogress !== undefined && (this.xhr.onprogress = this._onProgress);
if (this.loadType !== LoaderBase.typeText) {
if (!checkIfGoodValue.call(this)) {
console.warn('Attempting to use incompatible load type ' + this.loadType + '. Switching it to ' + LoaderBase.typeText);
this.loadType = LoaderBase.typeText;
}
try {
this.loadTypeSet = checkResponseTypeSupport.call(this) && checkAndSetType(this.xhr, this.loadType);
} catch (e) {
this.loadTypeSet = false;
}
if (!this.loadTypeSet && (this.loadType === LoaderBase.typeBlob || this.loadType === LoaderBase.typeArraybuffer)) {
this.xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
}
this.xhr.send();
}
}
|
[
"function",
"(",
"url",
")",
"{",
"this",
".",
"url",
"=",
"url",
";",
"if",
"(",
"this",
".",
"canLoadUsingXHR",
"(",
")",
")",
"{",
"this",
".",
"xhr",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"this",
".",
"xhr",
".",
"open",
"(",
"'GET'",
",",
"url",
",",
"true",
")",
";",
"this",
".",
"xhr",
".",
"onreadystatechange",
"=",
"this",
".",
"_onStateChange",
";",
"this",
".",
"xhr",
".",
"onprogress",
"!==",
"undefined",
"&&",
"(",
"this",
".",
"xhr",
".",
"onprogress",
"=",
"this",
".",
"_onProgress",
")",
";",
"if",
"(",
"this",
".",
"loadType",
"!==",
"LoaderBase",
".",
"typeText",
")",
"{",
"if",
"(",
"!",
"checkIfGoodValue",
".",
"call",
"(",
"this",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'Attempting to use incompatible load type '",
"+",
"this",
".",
"loadType",
"+",
"'. Switching it to '",
"+",
"LoaderBase",
".",
"typeText",
")",
";",
"this",
".",
"loadType",
"=",
"LoaderBase",
".",
"typeText",
";",
"}",
"try",
"{",
"this",
".",
"loadTypeSet",
"=",
"checkResponseTypeSupport",
".",
"call",
"(",
"this",
")",
"&&",
"checkAndSetType",
"(",
"this",
".",
"xhr",
",",
"this",
".",
"loadType",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"loadTypeSet",
"=",
"false",
";",
"}",
"if",
"(",
"!",
"this",
".",
"loadTypeSet",
"&&",
"(",
"this",
".",
"loadType",
"===",
"LoaderBase",
".",
"typeBlob",
"||",
"this",
".",
"loadType",
"===",
"LoaderBase",
".",
"typeArraybuffer",
")",
")",
"{",
"this",
".",
"xhr",
".",
"overrideMimeType",
"(",
"'text/plain; charset=x-user-defined'",
")",
";",
"}",
"}",
"this",
".",
"xhr",
".",
"send",
"(",
")",
";",
"}",
"}"
] |
The load function should be called to start preloading data.
The first parameter passed to the load function is the url to the data to be loaded.
It should be noted that mimetype for binary Blob data is read from
the file extension. EG. jpg will use the mimetype "image/jpeg".
@method load
@param {String} url This is the url to the data to be loaded
|
[
"The",
"load",
"function",
"should",
"be",
"called",
"to",
"start",
"preloading",
"data",
"."
] |
f094e19a423245f50def5fa37b3702d5eb4852ea
|
https://github.com/Jam3/preloader/blob/f094e19a423245f50def5fa37b3702d5eb4852ea/lib/loaders/LoaderBase.js#L74-L103
|
|
9,981
|
Jam3/preloader
|
lib/loaders/LoaderBase.js
|
function (ev) {
var loaded = ev.loaded || ev.position;
var totalSize = ev.total || ev.totalSize;
if (totalSize) {
this._dispatchProgress(loaded / totalSize);
} else {
this._dispatchProgress(0);
}
}
|
javascript
|
function (ev) {
var loaded = ev.loaded || ev.position;
var totalSize = ev.total || ev.totalSize;
if (totalSize) {
this._dispatchProgress(loaded / totalSize);
} else {
this._dispatchProgress(0);
}
}
|
[
"function",
"(",
"ev",
")",
"{",
"var",
"loaded",
"=",
"ev",
".",
"loaded",
"||",
"ev",
".",
"position",
";",
"var",
"totalSize",
"=",
"ev",
".",
"total",
"||",
"ev",
".",
"totalSize",
";",
"if",
"(",
"totalSize",
")",
"{",
"this",
".",
"_dispatchProgress",
"(",
"loaded",
"/",
"totalSize",
")",
";",
"}",
"else",
"{",
"this",
".",
"_dispatchProgress",
"(",
"0",
")",
";",
"}",
"}"
] |
This callback will be called when the XHR progresses in its load.
@method _onProgress
@protected
@param {XMLHttpRequestProgressEvent} ev This event contains data for the progress of the load
|
[
"This",
"callback",
"will",
"be",
"called",
"when",
"the",
"XHR",
"progresses",
"in",
"its",
"load",
"."
] |
f094e19a423245f50def5fa37b3702d5eb4852ea
|
https://github.com/Jam3/preloader/blob/f094e19a423245f50def5fa37b3702d5eb4852ea/lib/loaders/LoaderBase.js#L167-L176
|
|
9,982
|
Jam3/preloader
|
lib/loaders/LoaderBase.js
|
function () {
if (this.xhr.readyState > 1) {
var status;
var waiting = false;
// Fix error in IE8 where status isn't available until readyState=4
try { status = this.xhr.status; } catch (e) { waiting = true; }
if (status === 200) {
switch (this.xhr.readyState) {
// send() has been called, and headers and status are available
case 2:
this.fileMeta = new FileMeta(this.xhr.getAllResponseHeaders());
this._dispatchStart();
break;
// Downloading; responseText holds partial data.
case 3:
// todo progress could be calculated here if onprogress does not exist on XHR
// this.onProgress.dispatch();
break;
// Done
case 4:
this._parseContent();
this._dispatchComplete();
break;
}
} else if (!waiting) {
this.xhr.onreadystatechange = undefined;
this._dispatchError(this.xhr.status);
}
}
}
|
javascript
|
function () {
if (this.xhr.readyState > 1) {
var status;
var waiting = false;
// Fix error in IE8 where status isn't available until readyState=4
try { status = this.xhr.status; } catch (e) { waiting = true; }
if (status === 200) {
switch (this.xhr.readyState) {
// send() has been called, and headers and status are available
case 2:
this.fileMeta = new FileMeta(this.xhr.getAllResponseHeaders());
this._dispatchStart();
break;
// Downloading; responseText holds partial data.
case 3:
// todo progress could be calculated here if onprogress does not exist on XHR
// this.onProgress.dispatch();
break;
// Done
case 4:
this._parseContent();
this._dispatchComplete();
break;
}
} else if (!waiting) {
this.xhr.onreadystatechange = undefined;
this._dispatchError(this.xhr.status);
}
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"xhr",
".",
"readyState",
">",
"1",
")",
"{",
"var",
"status",
";",
"var",
"waiting",
"=",
"false",
";",
"// Fix error in IE8 where status isn't available until readyState=4",
"try",
"{",
"status",
"=",
"this",
".",
"xhr",
".",
"status",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"waiting",
"=",
"true",
";",
"}",
"if",
"(",
"status",
"===",
"200",
")",
"{",
"switch",
"(",
"this",
".",
"xhr",
".",
"readyState",
")",
"{",
"// send() has been called, and headers and status are available",
"case",
"2",
":",
"this",
".",
"fileMeta",
"=",
"new",
"FileMeta",
"(",
"this",
".",
"xhr",
".",
"getAllResponseHeaders",
"(",
")",
")",
";",
"this",
".",
"_dispatchStart",
"(",
")",
";",
"break",
";",
"// Downloading; responseText holds partial data.",
"case",
"3",
":",
"// todo progress could be calculated here if onprogress does not exist on XHR",
"// this.onProgress.dispatch();",
"break",
";",
"// Done",
"case",
"4",
":",
"this",
".",
"_parseContent",
"(",
")",
";",
"this",
".",
"_dispatchComplete",
"(",
")",
";",
"break",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"waiting",
")",
"{",
"this",
".",
"xhr",
".",
"onreadystatechange",
"=",
"undefined",
";",
"this",
".",
"_dispatchError",
"(",
"this",
".",
"xhr",
".",
"status",
")",
";",
"}",
"}",
"}"
] |
This function is called whenever the readyState of the XHR object changes.
this.xhr.readyState == 2 //send() has been called, and headers and status are available
this.xhr.readyState == 3 //Downloading; responseText holds partial data.
this.xhr.readyState == 4 //Done
You should also handle HTTP error status codes:
this.xhr.status == 404 //file doesn't exist
@method _onStateChange
@protected
|
[
"This",
"function",
"is",
"called",
"whenever",
"the",
"readyState",
"of",
"the",
"XHR",
"object",
"changes",
"."
] |
f094e19a423245f50def5fa37b3702d5eb4852ea
|
https://github.com/Jam3/preloader/blob/f094e19a423245f50def5fa37b3702d5eb4852ea/lib/loaders/LoaderBase.js#L192-L230
|
|
9,983
|
Jam3/preloader
|
lib/loaders/LoaderBase.js
|
function () {
if (this.loadTypeSet || this.loadType === LoaderBase.typeText) {
this.content = this.xhr.response || this.xhr.responseText;
} else {
switch (this.loadType) {
case LoaderBase.typeArraybuffer:
if (ArrayBuffer) {
this.content = stringToArrayBuffer(this.xhr.response);
} else {
throw new Error('This browser does not support ArrayBuffer');
}
break;
case LoaderBase.typeBlob:
case LoaderBase.typeVideo:
case LoaderBase.typeAudio:
if (Blob) {
if (!this.fileMeta) {
this.fileMeta = new FileMeta();
}
if (this.fileMeta.mime === null) {
this.fileMeta.mime = getMimeFromURL(this.url);
}
this.content = new Blob([ stringToArrayBuffer(this.xhr.response) ], { type: this.fileMeta.mime });
} else {
throw new Error('This browser does not support Blob');
}
break;
case LoaderBase.typeJSON:
this.content = JSON.parse(this.xhr.response);
break;
case LoaderBase.typeDocument:
// this needs some work pretty sure there's a better way to handle this
this.content = this.xhr.response;
break;
}
}
}
|
javascript
|
function () {
if (this.loadTypeSet || this.loadType === LoaderBase.typeText) {
this.content = this.xhr.response || this.xhr.responseText;
} else {
switch (this.loadType) {
case LoaderBase.typeArraybuffer:
if (ArrayBuffer) {
this.content = stringToArrayBuffer(this.xhr.response);
} else {
throw new Error('This browser does not support ArrayBuffer');
}
break;
case LoaderBase.typeBlob:
case LoaderBase.typeVideo:
case LoaderBase.typeAudio:
if (Blob) {
if (!this.fileMeta) {
this.fileMeta = new FileMeta();
}
if (this.fileMeta.mime === null) {
this.fileMeta.mime = getMimeFromURL(this.url);
}
this.content = new Blob([ stringToArrayBuffer(this.xhr.response) ], { type: this.fileMeta.mime });
} else {
throw new Error('This browser does not support Blob');
}
break;
case LoaderBase.typeJSON:
this.content = JSON.parse(this.xhr.response);
break;
case LoaderBase.typeDocument:
// this needs some work pretty sure there's a better way to handle this
this.content = this.xhr.response;
break;
}
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"loadTypeSet",
"||",
"this",
".",
"loadType",
"===",
"LoaderBase",
".",
"typeText",
")",
"{",
"this",
".",
"content",
"=",
"this",
".",
"xhr",
".",
"response",
"||",
"this",
".",
"xhr",
".",
"responseText",
";",
"}",
"else",
"{",
"switch",
"(",
"this",
".",
"loadType",
")",
"{",
"case",
"LoaderBase",
".",
"typeArraybuffer",
":",
"if",
"(",
"ArrayBuffer",
")",
"{",
"this",
".",
"content",
"=",
"stringToArrayBuffer",
"(",
"this",
".",
"xhr",
".",
"response",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'This browser does not support ArrayBuffer'",
")",
";",
"}",
"break",
";",
"case",
"LoaderBase",
".",
"typeBlob",
":",
"case",
"LoaderBase",
".",
"typeVideo",
":",
"case",
"LoaderBase",
".",
"typeAudio",
":",
"if",
"(",
"Blob",
")",
"{",
"if",
"(",
"!",
"this",
".",
"fileMeta",
")",
"{",
"this",
".",
"fileMeta",
"=",
"new",
"FileMeta",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"fileMeta",
".",
"mime",
"===",
"null",
")",
"{",
"this",
".",
"fileMeta",
".",
"mime",
"=",
"getMimeFromURL",
"(",
"this",
".",
"url",
")",
";",
"}",
"this",
".",
"content",
"=",
"new",
"Blob",
"(",
"[",
"stringToArrayBuffer",
"(",
"this",
".",
"xhr",
".",
"response",
")",
"]",
",",
"{",
"type",
":",
"this",
".",
"fileMeta",
".",
"mime",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'This browser does not support Blob'",
")",
";",
"}",
"break",
";",
"case",
"LoaderBase",
".",
"typeJSON",
":",
"this",
".",
"content",
"=",
"JSON",
".",
"parse",
"(",
"this",
".",
"xhr",
".",
"response",
")",
";",
"break",
";",
"case",
"LoaderBase",
".",
"typeDocument",
":",
"// this needs some work pretty sure there's a better way to handle this",
"this",
".",
"content",
"=",
"this",
".",
"xhr",
".",
"response",
";",
"break",
";",
"}",
"}",
"}"
] |
This function will grab the response from the content loaded and parse it out
@method _parseContent
@protected
|
[
"This",
"function",
"will",
"grab",
"the",
"response",
"from",
"the",
"content",
"loaded",
"and",
"parse",
"it",
"out"
] |
f094e19a423245f50def5fa37b3702d5eb4852ea
|
https://github.com/Jam3/preloader/blob/f094e19a423245f50def5fa37b3702d5eb4852ea/lib/loaders/LoaderBase.js#L238-L285
|
|
9,984
|
vizabi/vizabi
|
src/base/events.js
|
freezeAll
|
function freezeAll(exceptions) {
_freezeAllEvents = true;
if (!exceptions) {
return;
}
if (!utils.isArray(exceptions)) {
exceptions = [exceptions];
}
utils.forEach(exceptions, e => {
_freezeAllExceptions[e] = true;
});
}
|
javascript
|
function freezeAll(exceptions) {
_freezeAllEvents = true;
if (!exceptions) {
return;
}
if (!utils.isArray(exceptions)) {
exceptions = [exceptions];
}
utils.forEach(exceptions, e => {
_freezeAllExceptions[e] = true;
});
}
|
[
"function",
"freezeAll",
"(",
"exceptions",
")",
"{",
"_freezeAllEvents",
"=",
"true",
";",
"if",
"(",
"!",
"exceptions",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"utils",
".",
"isArray",
"(",
"exceptions",
")",
")",
"{",
"exceptions",
"=",
"[",
"exceptions",
"]",
";",
"}",
"utils",
".",
"forEach",
"(",
"exceptions",
",",
"e",
"=>",
"{",
"_freezeAllExceptions",
"[",
"e",
"]",
"=",
"true",
";",
"}",
")",
";",
"}"
] |
generic event functions
freezes all events
|
[
"generic",
"event",
"functions",
"freezes",
"all",
"events"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/events.js#L323-L334
|
9,985
|
vizabi/vizabi
|
src/base/events.js
|
unfreezeAll
|
function unfreezeAll() {
_freezeAllEvents = false;
_freezeAllExceptions = {};
//unfreeze all instances
const keys = Object.keys(_frozenEventInstances);
for (let i = 0; i < keys.length; i++) {
const instance = _frozenEventInstances[keys[i]];
if (!instance) {
continue;
}
instance.unfreeze();
}
_frozenEventInstances = {};
}
|
javascript
|
function unfreezeAll() {
_freezeAllEvents = false;
_freezeAllExceptions = {};
//unfreeze all instances
const keys = Object.keys(_frozenEventInstances);
for (let i = 0; i < keys.length; i++) {
const instance = _frozenEventInstances[keys[i]];
if (!instance) {
continue;
}
instance.unfreeze();
}
_frozenEventInstances = {};
}
|
[
"function",
"unfreezeAll",
"(",
")",
"{",
"_freezeAllEvents",
"=",
"false",
";",
"_freezeAllExceptions",
"=",
"{",
"}",
";",
"//unfreeze all instances",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"_frozenEventInstances",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"instance",
"=",
"_frozenEventInstances",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"!",
"instance",
")",
"{",
"continue",
";",
"}",
"instance",
".",
"unfreeze",
"(",
")",
";",
"}",
"_frozenEventInstances",
"=",
"{",
"}",
";",
"}"
] |
triggers all frozen events form all instances
|
[
"triggers",
"all",
"frozen",
"events",
"form",
"all",
"instances"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/events.js#L339-L352
|
9,986
|
vizabi/vizabi
|
src/base/component.js
|
_mapOne
|
function _mapOne(name) {
const parts = name.split(".");
let current = _this.parent.model;
let current_name = "";
while (parts.length) {
current_name = parts.shift();
current = current[current_name];
}
return {
name,
model: current,
type: current ? current.getType() : null
};
}
|
javascript
|
function _mapOne(name) {
const parts = name.split(".");
let current = _this.parent.model;
let current_name = "";
while (parts.length) {
current_name = parts.shift();
current = current[current_name];
}
return {
name,
model: current,
type: current ? current.getType() : null
};
}
|
[
"function",
"_mapOne",
"(",
"name",
")",
"{",
"const",
"parts",
"=",
"name",
".",
"split",
"(",
"\".\"",
")",
";",
"let",
"current",
"=",
"_this",
".",
"parent",
".",
"model",
";",
"let",
"current_name",
"=",
"\"\"",
";",
"while",
"(",
"parts",
".",
"length",
")",
"{",
"current_name",
"=",
"parts",
".",
"shift",
"(",
")",
";",
"current",
"=",
"current",
"[",
"current_name",
"]",
";",
"}",
"return",
"{",
"name",
",",
"model",
":",
"current",
",",
"type",
":",
"current",
"?",
"current",
".",
"getType",
"(",
")",
":",
"null",
"}",
";",
"}"
] |
Maps one model name to current submodel and returns info
@param {String} name Full model path. E.g.: "state.marker.color"
@returns {Object} the model info, with name and the actual model
|
[
"Maps",
"one",
"model",
"name",
"to",
"current",
"submodel",
"and",
"returns",
"info"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/component.js#L439-L452
|
9,987
|
vizabi/vizabi
|
src/base/component.js
|
templateFunc
|
function templateFunc(str, data) {
const func = function(obj) {
return str.replace(/<%=([^%]*)%>/g, match => {
//match t("...")
let s = match.match(/t\s*\(([^)]+)\)/g);
//replace with translation
if (s.length) {
s = obj.t(s[0].match(/"([^"]+)"/g)[0].split('"').join(""));
}
//use object[name]
else {
s = match.match(/([a-z\-A-Z]+([a-z\-A-Z0-9]?[a-zA-Z0-9]?)?)/g)[0];
s = obj[s] || s;
}
return s;
});
};
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
const fn = !/<[a-z][\s\S]*>/i.test(str) ? templates[str] = templates[str] || templateFunc(globals.templates[str]) : func;
// Provide some basic currying to the user
return data ? fn(data) : fn;
}
|
javascript
|
function templateFunc(str, data) {
const func = function(obj) {
return str.replace(/<%=([^%]*)%>/g, match => {
//match t("...")
let s = match.match(/t\s*\(([^)]+)\)/g);
//replace with translation
if (s.length) {
s = obj.t(s[0].match(/"([^"]+)"/g)[0].split('"').join(""));
}
//use object[name]
else {
s = match.match(/([a-z\-A-Z]+([a-z\-A-Z0-9]?[a-zA-Z0-9]?)?)/g)[0];
s = obj[s] || s;
}
return s;
});
};
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
const fn = !/<[a-z][\s\S]*>/i.test(str) ? templates[str] = templates[str] || templateFunc(globals.templates[str]) : func;
// Provide some basic currying to the user
return data ? fn(data) : fn;
}
|
[
"function",
"templateFunc",
"(",
"str",
",",
"data",
")",
"{",
"const",
"func",
"=",
"function",
"(",
"obj",
")",
"{",
"return",
"str",
".",
"replace",
"(",
"/",
"<%=([^%]*)%>",
"/",
"g",
",",
"match",
"=>",
"{",
"//match t(\"...\")",
"let",
"s",
"=",
"match",
".",
"match",
"(",
"/",
"t\\s*\\(([^)]+)\\)",
"/",
"g",
")",
";",
"//replace with translation",
"if",
"(",
"s",
".",
"length",
")",
"{",
"s",
"=",
"obj",
".",
"t",
"(",
"s",
"[",
"0",
"]",
".",
"match",
"(",
"/",
"\"([^\"]+)\"",
"/",
"g",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'\"'",
")",
".",
"join",
"(",
"\"\"",
")",
")",
";",
"}",
"//use object[name]",
"else",
"{",
"s",
"=",
"match",
".",
"match",
"(",
"/",
"([a-z\\-A-Z]+([a-z\\-A-Z0-9]?[a-zA-Z0-9]?)?)",
"/",
"g",
")",
"[",
"0",
"]",
";",
"s",
"=",
"obj",
"[",
"s",
"]",
"||",
"s",
";",
"}",
"return",
"s",
";",
"}",
")",
";",
"}",
";",
"// Figure out if we're getting a template, or if we need to",
"// load the template - and be sure to cache the result.",
"const",
"fn",
"=",
"!",
"/",
"<[a-z][\\s\\S]*>",
"/",
"i",
".",
"test",
"(",
"str",
")",
"?",
"templates",
"[",
"str",
"]",
"=",
"templates",
"[",
"str",
"]",
"||",
"templateFunc",
"(",
"globals",
".",
"templates",
"[",
"str",
"]",
")",
":",
"func",
";",
"// Provide some basic currying to the user",
"return",
"data",
"?",
"fn",
"(",
"data",
")",
":",
"fn",
";",
"}"
] |
Based on Simple JavaScript Templating by John Resig generic templating function
|
[
"Based",
"on",
"Simple",
"JavaScript",
"Templating",
"by",
"John",
"Resig",
"generic",
"templating",
"function"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/component.js#L549-L573
|
9,988
|
vizabi/vizabi
|
src/base/model.js
|
initSubmodel
|
function initSubmodel(attr, val, ctx, persistent) {
let submodel;
// if value is a value -> leaf
if (!utils.isPlainObject(val) || utils.isArray(val) || ctx.isObjectLeaf(attr)) {
const binds = {
//the submodel has changed (multiple times)
"change": onChange
};
submodel = new ModelLeaf(attr, val, ctx, binds, persistent);
}
// if value is an object -> model
else {
const binds = {
//the submodel has changed (multiple times)
"change": onChange,
//loading has started in this submodel (multiple times)
"hook_change": onHookChange,
// error triggered in loading
"load_error": (...args) => ctx.trigger(...args),
// interpolation completed
"dataLoaded": (...args) => ctx.trigger(...args),
//loading has ended in this submodel (multiple times)
"ready": onReady,
};
// if the value is an already instantiated submodel (Model or ModelLeaf)
// this is the case for example when a new componentmodel is made (in Component._modelMapping)
// it takes the submodels from the toolmodel and creates a new model for the component which refers
// to the instantiated submodels (by passing them as model values, and thus they reach here)
if (Model.isModel(val, true)) {
submodel = val;
submodel.on(binds);
}
// if it's just a plain object, create a new model
else {
// construct model
const modelType = attr.split("_")[0];
let Modl = Model.get(modelType, true);
if (!Modl) {
try {
Modl = require("../models/" + modelType).default;
} catch (err) {
Modl = Model;
}
}
submodel = new Modl(attr, val, ctx, binds);
// model is still frozen but will be unfrozen at end of original .set()
}
}
return submodel;
// Default event handlers for models
function onChange(evt, path) {
if (!ctx._ready) return; //block change propagation if model isnt ready
path = ctx._name + "." + path;
ctx.trigger(evt, path);
}
function onHookChange(evt, vals) {
ctx.trigger(evt, vals);
}
function onReady(evt, vals) {
//trigger only for submodel
ctx.setReady(false);
//wait to make sure it's not set false again in the next execution loop
utils.defer(() => {
ctx.setReady();
});
//ctx.trigger(evt, vals);
}
}
|
javascript
|
function initSubmodel(attr, val, ctx, persistent) {
let submodel;
// if value is a value -> leaf
if (!utils.isPlainObject(val) || utils.isArray(val) || ctx.isObjectLeaf(attr)) {
const binds = {
//the submodel has changed (multiple times)
"change": onChange
};
submodel = new ModelLeaf(attr, val, ctx, binds, persistent);
}
// if value is an object -> model
else {
const binds = {
//the submodel has changed (multiple times)
"change": onChange,
//loading has started in this submodel (multiple times)
"hook_change": onHookChange,
// error triggered in loading
"load_error": (...args) => ctx.trigger(...args),
// interpolation completed
"dataLoaded": (...args) => ctx.trigger(...args),
//loading has ended in this submodel (multiple times)
"ready": onReady,
};
// if the value is an already instantiated submodel (Model or ModelLeaf)
// this is the case for example when a new componentmodel is made (in Component._modelMapping)
// it takes the submodels from the toolmodel and creates a new model for the component which refers
// to the instantiated submodels (by passing them as model values, and thus they reach here)
if (Model.isModel(val, true)) {
submodel = val;
submodel.on(binds);
}
// if it's just a plain object, create a new model
else {
// construct model
const modelType = attr.split("_")[0];
let Modl = Model.get(modelType, true);
if (!Modl) {
try {
Modl = require("../models/" + modelType).default;
} catch (err) {
Modl = Model;
}
}
submodel = new Modl(attr, val, ctx, binds);
// model is still frozen but will be unfrozen at end of original .set()
}
}
return submodel;
// Default event handlers for models
function onChange(evt, path) {
if (!ctx._ready) return; //block change propagation if model isnt ready
path = ctx._name + "." + path;
ctx.trigger(evt, path);
}
function onHookChange(evt, vals) {
ctx.trigger(evt, vals);
}
function onReady(evt, vals) {
//trigger only for submodel
ctx.setReady(false);
//wait to make sure it's not set false again in the next execution loop
utils.defer(() => {
ctx.setReady();
});
//ctx.trigger(evt, vals);
}
}
|
[
"function",
"initSubmodel",
"(",
"attr",
",",
"val",
",",
"ctx",
",",
"persistent",
")",
"{",
"let",
"submodel",
";",
"// if value is a value -> leaf",
"if",
"(",
"!",
"utils",
".",
"isPlainObject",
"(",
"val",
")",
"||",
"utils",
".",
"isArray",
"(",
"val",
")",
"||",
"ctx",
".",
"isObjectLeaf",
"(",
"attr",
")",
")",
"{",
"const",
"binds",
"=",
"{",
"//the submodel has changed (multiple times)",
"\"change\"",
":",
"onChange",
"}",
";",
"submodel",
"=",
"new",
"ModelLeaf",
"(",
"attr",
",",
"val",
",",
"ctx",
",",
"binds",
",",
"persistent",
")",
";",
"}",
"// if value is an object -> model",
"else",
"{",
"const",
"binds",
"=",
"{",
"//the submodel has changed (multiple times)",
"\"change\"",
":",
"onChange",
",",
"//loading has started in this submodel (multiple times)",
"\"hook_change\"",
":",
"onHookChange",
",",
"// error triggered in loading",
"\"load_error\"",
":",
"(",
"...",
"args",
")",
"=>",
"ctx",
".",
"trigger",
"(",
"...",
"args",
")",
",",
"// interpolation completed",
"\"dataLoaded\"",
":",
"(",
"...",
"args",
")",
"=>",
"ctx",
".",
"trigger",
"(",
"...",
"args",
")",
",",
"//loading has ended in this submodel (multiple times)",
"\"ready\"",
":",
"onReady",
",",
"}",
";",
"// if the value is an already instantiated submodel (Model or ModelLeaf)",
"// this is the case for example when a new componentmodel is made (in Component._modelMapping)",
"// it takes the submodels from the toolmodel and creates a new model for the component which refers",
"// to the instantiated submodels (by passing them as model values, and thus they reach here)",
"if",
"(",
"Model",
".",
"isModel",
"(",
"val",
",",
"true",
")",
")",
"{",
"submodel",
"=",
"val",
";",
"submodel",
".",
"on",
"(",
"binds",
")",
";",
"}",
"// if it's just a plain object, create a new model",
"else",
"{",
"// construct model",
"const",
"modelType",
"=",
"attr",
".",
"split",
"(",
"\"_\"",
")",
"[",
"0",
"]",
";",
"let",
"Modl",
"=",
"Model",
".",
"get",
"(",
"modelType",
",",
"true",
")",
";",
"if",
"(",
"!",
"Modl",
")",
"{",
"try",
"{",
"Modl",
"=",
"require",
"(",
"\"../models/\"",
"+",
"modelType",
")",
".",
"default",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"Modl",
"=",
"Model",
";",
"}",
"}",
"submodel",
"=",
"new",
"Modl",
"(",
"attr",
",",
"val",
",",
"ctx",
",",
"binds",
")",
";",
"// model is still frozen but will be unfrozen at end of original .set()",
"}",
"}",
"return",
"submodel",
";",
"// Default event handlers for models",
"function",
"onChange",
"(",
"evt",
",",
"path",
")",
"{",
"if",
"(",
"!",
"ctx",
".",
"_ready",
")",
"return",
";",
"//block change propagation if model isnt ready",
"path",
"=",
"ctx",
".",
"_name",
"+",
"\".\"",
"+",
"path",
";",
"ctx",
".",
"trigger",
"(",
"evt",
",",
"path",
")",
";",
"}",
"function",
"onHookChange",
"(",
"evt",
",",
"vals",
")",
"{",
"ctx",
".",
"trigger",
"(",
"evt",
",",
"vals",
")",
";",
"}",
"function",
"onReady",
"(",
"evt",
",",
"vals",
")",
"{",
"//trigger only for submodel",
"ctx",
".",
"setReady",
"(",
"false",
")",
";",
"//wait to make sure it's not set false again in the next execution loop",
"utils",
".",
"defer",
"(",
"(",
")",
"=>",
"{",
"ctx",
".",
"setReady",
"(",
")",
";",
"}",
")",
";",
"//ctx.trigger(evt, vals);",
"}",
"}"
] |
Loads a submodel, when necessaary
@param {String} attr Name of submodel
@param {Object} val Initial values
@param {Object} ctx context / parent model
@param {Boolean} persistent true if the change is a persistent change
@returns {Object} model new submodel
|
[
"Loads",
"a",
"submodel",
"when",
"necessaary"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/model.js#L707-L784
|
9,989
|
vizabi/vizabi
|
src/base/model.js
|
onChange
|
function onChange(evt, path) {
if (!ctx._ready) return; //block change propagation if model isnt ready
path = ctx._name + "." + path;
ctx.trigger(evt, path);
}
|
javascript
|
function onChange(evt, path) {
if (!ctx._ready) return; //block change propagation if model isnt ready
path = ctx._name + "." + path;
ctx.trigger(evt, path);
}
|
[
"function",
"onChange",
"(",
"evt",
",",
"path",
")",
"{",
"if",
"(",
"!",
"ctx",
".",
"_ready",
")",
"return",
";",
"//block change propagation if model isnt ready",
"path",
"=",
"ctx",
".",
"_name",
"+",
"\".\"",
"+",
"path",
";",
"ctx",
".",
"trigger",
"(",
"evt",
",",
"path",
")",
";",
"}"
] |
Default event handlers for models
|
[
"Default",
"event",
"handlers",
"for",
"models"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/model.js#L767-L771
|
9,990
|
vizabi/vizabi
|
src/base/model.js
|
getIntervals
|
function getIntervals(ctx) {
return ctx._intervals || (ctx._parent ? getIntervals(ctx._parent) : new Intervals());
}
|
javascript
|
function getIntervals(ctx) {
return ctx._intervals || (ctx._parent ? getIntervals(ctx._parent) : new Intervals());
}
|
[
"function",
"getIntervals",
"(",
"ctx",
")",
"{",
"return",
"ctx",
".",
"_intervals",
"||",
"(",
"ctx",
".",
"_parent",
"?",
"getIntervals",
"(",
"ctx",
".",
"_parent",
")",
":",
"new",
"Intervals",
"(",
")",
")",
";",
"}"
] |
gets closest interval from this model or parent
@returns {Object} Intervals object
|
[
"gets",
"closest",
"interval",
"from",
"this",
"model",
"or",
"parent"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/model.js#L790-L792
|
9,991
|
vizabi/vizabi
|
src/base/utils.js
|
function(val) {
if (val === undefined) {
return "undefined";
}
if (val === null) {
return "null";
}
let type = typeof val;
if (type === "object") {
type = getClass(val).toLowerCase();
}
if (type === "number") {
return val.toString().indexOf(".") > 0 ?
"float" :
"integer";
}
return type;
}
|
javascript
|
function(val) {
if (val === undefined) {
return "undefined";
}
if (val === null) {
return "null";
}
let type = typeof val;
if (type === "object") {
type = getClass(val).toLowerCase();
}
if (type === "number") {
return val.toString().indexOf(".") > 0 ?
"float" :
"integer";
}
return type;
}
|
[
"function",
"(",
"val",
")",
"{",
"if",
"(",
"val",
"===",
"undefined",
")",
"{",
"return",
"\"undefined\"",
";",
"}",
"if",
"(",
"val",
"===",
"null",
")",
"{",
"return",
"\"null\"",
";",
"}",
"let",
"type",
"=",
"typeof",
"val",
";",
"if",
"(",
"type",
"===",
"\"object\"",
")",
"{",
"type",
"=",
"getClass",
"(",
"val",
")",
".",
"toLowerCase",
"(",
")",
";",
"}",
"if",
"(",
"type",
"===",
"\"number\"",
")",
"{",
"return",
"val",
".",
"toString",
"(",
")",
".",
"indexOf",
"(",
"\".\"",
")",
">",
"0",
"?",
"\"float\"",
":",
"\"integer\"",
";",
"}",
"return",
"type",
";",
"}"
] |
Defines the type of the value, extended typeof
|
[
"Defines",
"the",
"type",
"of",
"the",
"value",
"extended",
"typeof"
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/utils.js#L187-L209
|
|
9,992
|
vizabi/vizabi
|
src/base/utils.js
|
function(a, b) {
if (a !== b) {
const atype = whatis(a);
const btype = whatis(b);
if (atype === btype) {
return _equal.hasOwnProperty(atype) ? _equal[atype](a, b) : a == b;
}
return false;
}
return true;
}
|
javascript
|
function(a, b) {
if (a !== b) {
const atype = whatis(a);
const btype = whatis(b);
if (atype === btype) {
return _equal.hasOwnProperty(atype) ? _equal[atype](a, b) : a == b;
}
return false;
}
return true;
}
|
[
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
"!==",
"b",
")",
"{",
"const",
"atype",
"=",
"whatis",
"(",
"a",
")",
";",
"const",
"btype",
"=",
"whatis",
"(",
"b",
")",
";",
"if",
"(",
"atype",
"===",
"btype",
")",
"{",
"return",
"_equal",
".",
"hasOwnProperty",
"(",
"atype",
")",
"?",
"_equal",
"[",
"atype",
"]",
"(",
"a",
",",
"b",
")",
":",
"a",
"==",
"b",
";",
"}",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Are two values equal, deep compare for objects and arrays.
@param a {any}
@param b {any}
@return {boolean} Are equal?
|
[
"Are",
"two",
"values",
"equal",
"deep",
"compare",
"for",
"objects",
"and",
"arrays",
"."
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/utils.js#L264-L277
|
|
9,993
|
vizabi/vizabi
|
src/base/utils.js
|
deepCloneArray
|
function deepCloneArray(arr) {
const clone = [];
forEach(arr, (item, index) => {
if (typeof item === "object" && item !== null) {
if (isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
|
javascript
|
function deepCloneArray(arr) {
const clone = [];
forEach(arr, (item, index) => {
if (typeof item === "object" && item !== null) {
if (isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
|
[
"function",
"deepCloneArray",
"(",
"arr",
")",
"{",
"const",
"clone",
"=",
"[",
"]",
";",
"forEach",
"(",
"arr",
",",
"(",
"item",
",",
"index",
")",
"=>",
"{",
"if",
"(",
"typeof",
"item",
"===",
"\"object\"",
"&&",
"item",
"!==",
"null",
")",
"{",
"if",
"(",
"isArray",
"(",
"item",
")",
")",
"{",
"clone",
"[",
"index",
"]",
"=",
"deepCloneArray",
"(",
"item",
")",
";",
"}",
"else",
"if",
"(",
"isSpecificValue",
"(",
"item",
")",
")",
"{",
"clone",
"[",
"index",
"]",
"=",
"cloneSpecificValue",
"(",
"item",
")",
";",
"}",
"else",
"{",
"clone",
"[",
"index",
"]",
"=",
"deepExtend",
"(",
"{",
"}",
",",
"item",
")",
";",
"}",
"}",
"else",
"{",
"clone",
"[",
"index",
"]",
"=",
"item",
";",
"}",
"}",
")",
";",
"return",
"clone",
";",
"}"
] |
Recursive cloning array.
|
[
"Recursive",
"cloning",
"array",
"."
] |
cc2a44d7bb25f356189d5a3d241a205a15324540
|
https://github.com/vizabi/vizabi/blob/cc2a44d7bb25f356189d5a3d241a205a15324540/src/base/utils.js#L396-L412
|
9,994
|
GoogleCloudPlatform/nodejs-repo-tools
|
src/utils/index.js
|
finish
|
function finish(err) {
if (!calledDone) {
calledDone = true;
exports.finalize(err, resolve, reject);
}
}
|
javascript
|
function finish(err) {
if (!calledDone) {
calledDone = true;
exports.finalize(err, resolve, reject);
}
}
|
[
"function",
"finish",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"calledDone",
")",
"{",
"calledDone",
"=",
"true",
";",
"exports",
".",
"finalize",
"(",
"err",
",",
"resolve",
",",
"reject",
")",
";",
"}",
"}"
] |
Exit helper so we don't call "cb" more than once
|
[
"Exit",
"helper",
"so",
"we",
"don",
"t",
"call",
"cb",
"more",
"than",
"once"
] |
703d1011302de7be376d2c5da0b3410b68538414
|
https://github.com/GoogleCloudPlatform/nodejs-repo-tools/blob/703d1011302de7be376d2c5da0b3410b68538414/src/utils/index.js#L394-L399
|
9,995
|
KingSora/OverlayScrollbars
|
js/OverlayScrollbars.js
|
function() {
return window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW];
}
|
javascript
|
function() {
return window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW];
}
|
[
"function",
"(",
")",
"{",
"return",
"window",
".",
"innerWidth",
"||",
"document",
".",
"documentElement",
"[",
"LEXICON",
".",
"cW",
"]",
"||",
"document",
".",
"body",
"[",
"LEXICON",
".",
"cW",
"]",
";",
"}"
] |
Gets the current window width.
@returns {Number|number} The current window width in pixel.
|
[
"Gets",
"the",
"current",
"window",
"width",
"."
] |
8e658d46e2d034a2525269d7c873bbe844762307
|
https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L112-L114
|
|
9,996
|
KingSora/OverlayScrollbars
|
js/OverlayScrollbars.js
|
function() {
return window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH];
}
|
javascript
|
function() {
return window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH];
}
|
[
"function",
"(",
")",
"{",
"return",
"window",
".",
"innerHeight",
"||",
"document",
".",
"documentElement",
"[",
"LEXICON",
".",
"cH",
"]",
"||",
"document",
".",
"body",
"[",
"LEXICON",
".",
"cH",
"]",
";",
"}"
] |
Gets the current window height.
@returns {Number|number} The current window height in pixel.
|
[
"Gets",
"the",
"current",
"window",
"height",
"."
] |
8e658d46e2d034a2525269d7c873bbe844762307
|
https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L120-L122
|
|
9,997
|
KingSora/OverlayScrollbars
|
js/OverlayScrollbars.js
|
function(event) {
if(event.preventDefault && event.cancelable)
event.preventDefault();
else
event.returnValue = false;
}
|
javascript
|
function(event) {
if(event.preventDefault && event.cancelable)
event.preventDefault();
else
event.returnValue = false;
}
|
[
"function",
"(",
"event",
")",
"{",
"if",
"(",
"event",
".",
"preventDefault",
"&&",
"event",
".",
"cancelable",
")",
"event",
".",
"preventDefault",
"(",
")",
";",
"else",
"event",
".",
"returnValue",
"=",
"false",
";",
"}"
] |
Prevents the default action of the given event.
@param event The event of which the default action shall be prevented.
|
[
"Prevents",
"the",
"default",
"action",
"of",
"the",
"given",
"event",
"."
] |
8e658d46e2d034a2525269d7c873bbe844762307
|
https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L179-L184
|
|
9,998
|
KingSora/OverlayScrollbars
|
js/OverlayScrollbars.js
|
function(event) {
event = event.originalEvent || event;
var strPage = 'page';
var strClient = 'client';
var strX = 'X';
var strY = 'Y';
var target = event.target || event.srcElement || document;
var eventDoc = target.ownerDocument || document;
var doc = eventDoc.documentElement;
var body = eventDoc.body;
//if touch event return return pageX/Y of it
if(event.touches !== undefined) {
var touch = event.touches[0];
return {
x : touch[strPage + strX],
y : touch[strPage + strY]
}
}
// Calculate pageX/Y if not native supported
if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) {
return {
x : event[strClient + strX] +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0),
y : event[strClient + strY] +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0)
}
}
return {
x : event[strPage + strX],
y : event[strPage + strY]
};
}
|
javascript
|
function(event) {
event = event.originalEvent || event;
var strPage = 'page';
var strClient = 'client';
var strX = 'X';
var strY = 'Y';
var target = event.target || event.srcElement || document;
var eventDoc = target.ownerDocument || document;
var doc = eventDoc.documentElement;
var body = eventDoc.body;
//if touch event return return pageX/Y of it
if(event.touches !== undefined) {
var touch = event.touches[0];
return {
x : touch[strPage + strX],
y : touch[strPage + strY]
}
}
// Calculate pageX/Y if not native supported
if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) {
return {
x : event[strClient + strX] +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0),
y : event[strClient + strY] +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0)
}
}
return {
x : event[strPage + strX],
y : event[strPage + strY]
};
}
|
[
"function",
"(",
"event",
")",
"{",
"event",
"=",
"event",
".",
"originalEvent",
"||",
"event",
";",
"var",
"strPage",
"=",
"'page'",
";",
"var",
"strClient",
"=",
"'client'",
";",
"var",
"strX",
"=",
"'X'",
";",
"var",
"strY",
"=",
"'Y'",
";",
"var",
"target",
"=",
"event",
".",
"target",
"||",
"event",
".",
"srcElement",
"||",
"document",
";",
"var",
"eventDoc",
"=",
"target",
".",
"ownerDocument",
"||",
"document",
";",
"var",
"doc",
"=",
"eventDoc",
".",
"documentElement",
";",
"var",
"body",
"=",
"eventDoc",
".",
"body",
";",
"//if touch event return return pageX/Y of it",
"if",
"(",
"event",
".",
"touches",
"!==",
"undefined",
")",
"{",
"var",
"touch",
"=",
"event",
".",
"touches",
"[",
"0",
"]",
";",
"return",
"{",
"x",
":",
"touch",
"[",
"strPage",
"+",
"strX",
"]",
",",
"y",
":",
"touch",
"[",
"strPage",
"+",
"strY",
"]",
"}",
"}",
"// Calculate pageX/Y if not native supported",
"if",
"(",
"!",
"event",
"[",
"strPage",
"+",
"strX",
"]",
"&&",
"event",
"[",
"strClient",
"+",
"strX",
"]",
"&&",
"event",
"[",
"strClient",
"+",
"strX",
"]",
"!=",
"null",
")",
"{",
"return",
"{",
"x",
":",
"event",
"[",
"strClient",
"+",
"strX",
"]",
"+",
"(",
"doc",
"&&",
"doc",
".",
"scrollLeft",
"||",
"body",
"&&",
"body",
".",
"scrollLeft",
"||",
"0",
")",
"-",
"(",
"doc",
"&&",
"doc",
".",
"clientLeft",
"||",
"body",
"&&",
"body",
".",
"clientLeft",
"||",
"0",
")",
",",
"y",
":",
"event",
"[",
"strClient",
"+",
"strY",
"]",
"+",
"(",
"doc",
"&&",
"doc",
".",
"scrollTop",
"||",
"body",
"&&",
"body",
".",
"scrollTop",
"||",
"0",
")",
"-",
"(",
"doc",
"&&",
"doc",
".",
"clientTop",
"||",
"body",
"&&",
"body",
".",
"clientTop",
"||",
"0",
")",
"}",
"}",
"return",
"{",
"x",
":",
"event",
"[",
"strPage",
"+",
"strX",
"]",
",",
"y",
":",
"event",
"[",
"strPage",
"+",
"strY",
"]",
"}",
";",
"}"
] |
Gets the pageX and pageY values of the given mouse event.
@param event The mouse event of which the pageX and pageX shall be got.
@returns {{x: number, y: number}} x = pageX value, y = pageY value.
|
[
"Gets",
"the",
"pageX",
"and",
"pageY",
"values",
"of",
"the",
"given",
"mouse",
"event",
"."
] |
8e658d46e2d034a2525269d7c873bbe844762307
|
https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L191-L228
|
|
9,999
|
KingSora/OverlayScrollbars
|
js/OverlayScrollbars.js
|
function(event) {
var button = event.button;
if (!event.which && button !== undefined)
return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
else
return event.which;
}
|
javascript
|
function(event) {
var button = event.button;
if (!event.which && button !== undefined)
return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
else
return event.which;
}
|
[
"function",
"(",
"event",
")",
"{",
"var",
"button",
"=",
"event",
".",
"button",
";",
"if",
"(",
"!",
"event",
".",
"which",
"&&",
"button",
"!==",
"undefined",
")",
"return",
"(",
"button",
"&",
"1",
"?",
"1",
":",
"(",
"button",
"&",
"2",
"?",
"3",
":",
"(",
"button",
"&",
"4",
"?",
"2",
":",
"0",
")",
")",
")",
";",
"else",
"return",
"event",
".",
"which",
";",
"}"
] |
Gets the clicked mouse button of the given mouse event.
@param event The mouse event of which the clicked button shal be got.
@returns {number} The number of the clicked mouse button. (0 : none | 1 : leftButton | 2 : middleButton | 3 : rightButton)
|
[
"Gets",
"the",
"clicked",
"mouse",
"button",
"of",
"the",
"given",
"mouse",
"event",
"."
] |
8e658d46e2d034a2525269d7c873bbe844762307
|
https://github.com/KingSora/OverlayScrollbars/blob/8e658d46e2d034a2525269d7c873bbe844762307/js/OverlayScrollbars.js#L235-L241
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.