text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```javascript
//.CommonJS
var CSSOM = {};
///CommonJS
/**
* @constructor
* @see path_to_url#the-cssrule-interface
* @see path_to_url#CSS-CSSRule
*/
CSSOM.CSSRule = function CSSRule() {
this.parentRule = null;
this.parentStyleSheet = null;
};
CSSOM.CSSRule.UNKNOWN_RULE = 0; // obsolete
CSSOM.CSSRule.STYLE_RULE = 1;
CSSOM.CSSRule.CHARSET_RULE = 2; // obsolete
CSSOM.CSSRule.IMPORT_RULE = 3;
CSSOM.CSSRule.MEDIA_RULE = 4;
CSSOM.CSSRule.FONT_FACE_RULE = 5;
CSSOM.CSSRule.PAGE_RULE = 6;
CSSOM.CSSRule.KEYFRAMES_RULE = 7;
CSSOM.CSSRule.KEYFRAME_RULE = 8;
CSSOM.CSSRule.MARGIN_RULE = 9;
CSSOM.CSSRule.NAMESPACE_RULE = 10;
CSSOM.CSSRule.COUNTER_STYLE_RULE = 11;
CSSOM.CSSRule.SUPPORTS_RULE = 12;
CSSOM.CSSRule.DOCUMENT_RULE = 13;
CSSOM.CSSRule.FONT_FEATURE_VALUES_RULE = 14;
CSSOM.CSSRule.VIEWPORT_RULE = 15;
CSSOM.CSSRule.REGION_STYLE_RULE = 16;
CSSOM.CSSRule.prototype = {
constructor: CSSOM.CSSRule
//FIXME
};
//.CommonJS
exports.CSSRule = CSSOM.CSSRule;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/CSSRule.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 305 |
```javascript
//.CommonJS
var CSSOM = {
CSSRule: require("./CSSRule").CSSRule,
};
///CommonJS
/**
* @constructor
* @see path_to_url#the-csssupportsrule-interface
*/
CSSOM.CSSSupportsRule = function CSSSupportsRule() {
CSSOM.CSSRule.call(this);
this.conditionText = '';
this.cssRules = [];
};
CSSOM.CSSSupportsRule.prototype = new CSSOM.CSSRule();
CSSOM.CSSSupportsRule.prototype.constructor = CSSOM.CSSSupportsRule;
CSSOM.CSSSupportsRule.prototype.type = 12;
Object.defineProperty(CSSOM.CSSSupportsRule.prototype, "cssText", {
get: function() {
var cssTexts = [];
for (var i = 0, length = this.cssRules.length; i < length; i++) {
cssTexts.push(this.cssRules[i].cssText);
}
return "@supports " + this.conditionText + " {" + cssTexts.join("") + "}";
}
});
//.CommonJS
exports.CSSSupportsRule = CSSOM.CSSSupportsRule;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/CSSSupportsRule.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 236 |
```javascript
//.CommonJS
var CSSOM = {};
///CommonJS
/**
* @param {string} token
*/
CSSOM.parse = function parse(token) {
var i = 0;
/**
"before-selector" or
"selector" or
"atRule" or
"atBlock" or
"conditionBlock" or
"before-name" or
"name" or
"before-value" or
"value"
*/
var state = "before-selector";
var index;
var buffer = "";
var valueParenthesisDepth = 0;
var SIGNIFICANT_WHITESPACE = {
"selector": true,
"value": true,
"value-parenthesis": true,
"atRule": true,
"importRule-begin": true,
"importRule": true,
"atBlock": true,
"conditionBlock": true,
'documentRule-begin': true
};
var styleSheet = new CSSOM.CSSStyleSheet();
// @type CSSStyleSheet|CSSMediaRule|CSSSupportsRule|CSSFontFaceRule|CSSKeyframesRule|CSSDocumentRule
var currentScope = styleSheet;
// @type CSSMediaRule|CSSSupportsRule|CSSKeyframesRule|CSSDocumentRule
var parentRule;
var ancestorRules = [];
var hasAncestors = false;
var prevScope;
var name, priority="", styleRule, mediaRule, supportsRule, importRule, fontFaceRule, keyframesRule, documentRule, hostRule;
var atKeyframesRegExp = /@(-(?:\w+-)+)?keyframes/g;
var parseError = function(message) {
var lines = token.substring(0, i).split('\n');
var lineCount = lines.length;
var charCount = lines.pop().length + 1;
var error = new Error(message + ' (line ' + lineCount + ', char ' + charCount + ')');
error.line = lineCount;
/* jshint sub : true */
error['char'] = charCount;
error.styleSheet = styleSheet;
throw error;
};
for (var character; (character = token.charAt(i)); i++) {
switch (character) {
case " ":
case "\t":
case "\r":
case "\n":
case "\f":
if (SIGNIFICANT_WHITESPACE[state]) {
buffer += character;
}
break;
// String
case '"':
index = i + 1;
do {
index = token.indexOf('"', index) + 1;
if (!index) {
parseError('Unmatched "');
}
} while (token[index - 2] === '\\');
buffer += token.slice(i, index);
i = index - 1;
switch (state) {
case 'before-value':
state = 'value';
break;
case 'importRule-begin':
state = 'importRule';
break;
}
break;
case "'":
index = i + 1;
do {
index = token.indexOf("'", index) + 1;
if (!index) {
parseError("Unmatched '");
}
} while (token[index - 2] === '\\');
buffer += token.slice(i, index);
i = index - 1;
switch (state) {
case 'before-value':
state = 'value';
break;
case 'importRule-begin':
state = 'importRule';
break;
}
break;
// Comment
case "/":
if (token.charAt(i + 1) === "*") {
i += 2;
index = token.indexOf("*/", i);
if (index === -1) {
parseError("Missing */");
} else {
i = index + 1;
}
} else {
buffer += character;
}
if (state === "importRule-begin") {
buffer += " ";
state = "importRule";
}
break;
// At-rule
case "@":
if (token.indexOf("@-moz-document", i) === i) {
state = "documentRule-begin";
documentRule = new CSSOM.CSSDocumentRule();
documentRule.__starts = i;
i += "-moz-document".length;
buffer = "";
break;
} else if (token.indexOf("@media", i) === i) {
state = "atBlock";
mediaRule = new CSSOM.CSSMediaRule();
mediaRule.__starts = i;
i += "media".length;
buffer = "";
break;
} else if (token.indexOf("@supports", i) === i) {
state = "conditionBlock";
supportsRule = new CSSOM.CSSSupportsRule();
supportsRule.__starts = i;
i += "supports".length;
buffer = "";
break;
} else if (token.indexOf("@host", i) === i) {
state = "hostRule-begin";
i += "host".length;
hostRule = new CSSOM.CSSHostRule();
hostRule.__starts = i;
buffer = "";
break;
} else if (token.indexOf("@import", i) === i) {
state = "importRule-begin";
i += "import".length;
buffer += "@import";
break;
} else if (token.indexOf("@font-face", i) === i) {
state = "fontFaceRule-begin";
i += "font-face".length;
fontFaceRule = new CSSOM.CSSFontFaceRule();
fontFaceRule.__starts = i;
buffer = "";
break;
} else {
atKeyframesRegExp.lastIndex = i;
var matchKeyframes = atKeyframesRegExp.exec(token);
if (matchKeyframes && matchKeyframes.index === i) {
state = "keyframesRule-begin";
keyframesRule = new CSSOM.CSSKeyframesRule();
keyframesRule.__starts = i;
keyframesRule._vendorPrefix = matchKeyframes[1]; // Will come out as undefined if no prefix was found
i += matchKeyframes[0].length - 1;
buffer = "";
break;
} else if (state === "selector") {
state = "atRule";
}
}
buffer += character;
break;
case "{":
if (state === "selector" || state === "atRule") {
styleRule.selectorText = buffer.trim();
styleRule.style.__starts = i;
buffer = "";
state = "before-name";
} else if (state === "atBlock") {
mediaRule.media.mediaText = buffer.trim();
if (parentRule) {
ancestorRules.push(parentRule);
}
currentScope = parentRule = mediaRule;
mediaRule.parentStyleSheet = styleSheet;
buffer = "";
state = "before-selector";
} else if (state === "conditionBlock") {
supportsRule.conditionText = buffer.trim();
if (parentRule) {
ancestorRules.push(parentRule);
}
currentScope = parentRule = supportsRule;
supportsRule.parentStyleSheet = styleSheet;
buffer = "";
state = "before-selector";
} else if (state === "hostRule-begin") {
if (parentRule) {
ancestorRules.push(parentRule);
}
currentScope = parentRule = hostRule;
hostRule.parentStyleSheet = styleSheet;
buffer = "";
state = "before-selector";
} else if (state === "fontFaceRule-begin") {
if (parentRule) {
ancestorRules.push(parentRule);
fontFaceRule.parentRule = parentRule;
}
fontFaceRule.parentStyleSheet = styleSheet;
styleRule = fontFaceRule;
buffer = "";
state = "before-name";
} else if (state === "keyframesRule-begin") {
keyframesRule.name = buffer.trim();
if (parentRule) {
ancestorRules.push(parentRule);
keyframesRule.parentRule = parentRule;
}
keyframesRule.parentStyleSheet = styleSheet;
currentScope = parentRule = keyframesRule;
buffer = "";
state = "keyframeRule-begin";
} else if (state === "keyframeRule-begin") {
styleRule = new CSSOM.CSSKeyframeRule();
styleRule.keyText = buffer.trim();
styleRule.__starts = i;
buffer = "";
state = "before-name";
} else if (state === "documentRule-begin") {
// FIXME: what if this '{' is in the url text of the match function?
documentRule.matcher.matcherText = buffer.trim();
if (parentRule) {
ancestorRules.push(parentRule);
documentRule.parentRule = parentRule;
}
currentScope = parentRule = documentRule;
documentRule.parentStyleSheet = styleSheet;
buffer = "";
state = "before-selector";
}
break;
case ":":
if (state === "name") {
name = buffer.trim();
buffer = "";
state = "before-value";
} else {
buffer += character;
}
break;
case "(":
if (state === 'value') {
// ie css expression mode
if (buffer.trim() === 'expression') {
var info = (new CSSOM.CSSValueExpression(token, i)).parse();
if (info.error) {
parseError(info.error);
} else {
buffer += info.expression;
i = info.idx;
}
} else {
state = 'value-parenthesis';
//always ensure this is reset to 1 on transition
//from value to value-parenthesis
valueParenthesisDepth = 1;
buffer += character;
}
} else if (state === 'value-parenthesis') {
valueParenthesisDepth++;
buffer += character;
} else {
buffer += character;
}
break;
case ")":
if (state === 'value-parenthesis') {
valueParenthesisDepth--;
if (valueParenthesisDepth === 0) state = 'value';
}
buffer += character;
break;
case "!":
if (state === "value" && token.indexOf("!important", i) === i) {
priority = "important";
i += "important".length;
} else {
buffer += character;
}
break;
case ";":
switch (state) {
case "value":
styleRule.style.setProperty(name, buffer.trim(), priority);
priority = "";
buffer = "";
state = "before-name";
break;
case "atRule":
buffer = "";
state = "before-selector";
break;
case "importRule":
importRule = new CSSOM.CSSImportRule();
importRule.parentStyleSheet = importRule.styleSheet.parentStyleSheet = styleSheet;
importRule.cssText = buffer + character;
styleSheet.cssRules.push(importRule);
buffer = "";
state = "before-selector";
break;
default:
buffer += character;
break;
}
break;
case "}":
switch (state) {
case "value":
styleRule.style.setProperty(name, buffer.trim(), priority);
priority = "";
/* falls through */
case "before-name":
case "name":
styleRule.__ends = i + 1;
if (parentRule) {
styleRule.parentRule = parentRule;
}
styleRule.parentStyleSheet = styleSheet;
currentScope.cssRules.push(styleRule);
buffer = "";
if (currentScope.constructor === CSSOM.CSSKeyframesRule) {
state = "keyframeRule-begin";
} else {
state = "before-selector";
}
break;
case "keyframeRule-begin":
case "before-selector":
case "selector":
// End of media/supports/document rule.
if (!parentRule) {
parseError("Unexpected }");
}
// Handle rules nested in @media or @supports
hasAncestors = ancestorRules.length > 0;
while (ancestorRules.length > 0) {
parentRule = ancestorRules.pop();
if (
parentRule.constructor.name === "CSSMediaRule"
|| parentRule.constructor.name === "CSSSupportsRule"
) {
prevScope = currentScope;
currentScope = parentRule;
currentScope.cssRules.push(prevScope);
break;
}
if (ancestorRules.length === 0) {
hasAncestors = false;
}
}
if (!hasAncestors) {
currentScope.__ends = i + 1;
styleSheet.cssRules.push(currentScope);
currentScope = styleSheet;
parentRule = null;
}
buffer = "";
state = "before-selector";
break;
}
break;
default:
switch (state) {
case "before-selector":
state = "selector";
styleRule = new CSSOM.CSSStyleRule();
styleRule.__starts = i;
break;
case "before-name":
state = "name";
break;
case "before-value":
state = "value";
break;
case "importRule-begin":
state = "importRule";
break;
}
buffer += character;
break;
}
}
return styleSheet;
};
//.CommonJS
exports.parse = CSSOM.parse;
// The following modules cannot be included sooner due to the mutual dependency with parse.js
CSSOM.CSSStyleSheet = require("./CSSStyleSheet").CSSStyleSheet;
CSSOM.CSSStyleRule = require("./CSSStyleRule").CSSStyleRule;
CSSOM.CSSImportRule = require("./CSSImportRule").CSSImportRule;
CSSOM.CSSMediaRule = require("./CSSMediaRule").CSSMediaRule;
CSSOM.CSSSupportsRule = require("./CSSSupportsRule").CSSSupportsRule;
CSSOM.CSSFontFaceRule = require("./CSSFontFaceRule").CSSFontFaceRule;
CSSOM.CSSHostRule = require("./CSSHostRule").CSSHostRule;
CSSOM.CSSStyleDeclaration = require('./CSSStyleDeclaration').CSSStyleDeclaration;
CSSOM.CSSKeyframeRule = require('./CSSKeyframeRule').CSSKeyframeRule;
CSSOM.CSSKeyframesRule = require('./CSSKeyframesRule').CSSKeyframesRule;
CSSOM.CSSValueExpression = require('./CSSValueExpression').CSSValueExpression;
CSSOM.CSSDocumentRule = require('./CSSDocumentRule').CSSDocumentRule;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/parse.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,190 |
```javascript
//.CommonJS
var CSSOM = {
CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration,
CSSRule: require("./CSSRule").CSSRule
};
///CommonJS
/**
* @constructor
* @see path_to_url#css-font-face-rule
*/
CSSOM.CSSFontFaceRule = function CSSFontFaceRule() {
CSSOM.CSSRule.call(this);
this.style = new CSSOM.CSSStyleDeclaration();
this.style.parentRule = this;
};
CSSOM.CSSFontFaceRule.prototype = new CSSOM.CSSRule();
CSSOM.CSSFontFaceRule.prototype.constructor = CSSOM.CSSFontFaceRule;
CSSOM.CSSFontFaceRule.prototype.type = 5;
//FIXME
//CSSOM.CSSFontFaceRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule;
//CSSOM.CSSFontFaceRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule;
// path_to_url
Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "cssText", {
get: function() {
return "@font-face {" + this.style.cssText + "}";
}
});
//.CommonJS
exports.CSSFontFaceRule = CSSOM.CSSFontFaceRule;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/CSSFontFaceRule.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 245 |
```javascript
//.CommonJS
var CSSOM = {};
///CommonJS
/**
* @constructor
* @see path_to_url#the-medialist-interface
*/
CSSOM.MediaList = function MediaList(){
this.length = 0;
};
CSSOM.MediaList.prototype = {
constructor: CSSOM.MediaList,
/**
* @return {string}
*/
get mediaText() {
return Array.prototype.join.call(this, ", ");
},
/**
* @param {string} value
*/
set mediaText(value) {
var values = value.split(",");
var length = this.length = values.length;
for (var i=0; i<length; i++) {
this[i] = values[i].trim();
}
},
/**
* @param {string} medium
*/
appendMedium: function(medium) {
if (Array.prototype.indexOf.call(this, medium) === -1) {
this[this.length] = medium;
this.length++;
}
},
/**
* @param {string} medium
*/
deleteMedium: function(medium) {
var index = Array.prototype.indexOf.call(this, medium);
if (index !== -1) {
Array.prototype.splice.call(this, index, 1);
}
}
};
//.CommonJS
exports.MediaList = CSSOM.MediaList;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/MediaList.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 290 |
```javascript
//.CommonJS
var CSSOM = {
CSSRule: require("./CSSRule").CSSRule
};
///CommonJS
/**
* @constructor
* @see path_to_url#host-at-rule
*/
CSSOM.CSSHostRule = function CSSHostRule() {
CSSOM.CSSRule.call(this);
this.cssRules = [];
};
CSSOM.CSSHostRule.prototype = new CSSOM.CSSRule();
CSSOM.CSSHostRule.prototype.constructor = CSSOM.CSSHostRule;
CSSOM.CSSHostRule.prototype.type = 1001;
//FIXME
//CSSOM.CSSHostRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule;
//CSSOM.CSSHostRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule;
Object.defineProperty(CSSOM.CSSHostRule.prototype, "cssText", {
get: function() {
var cssTexts = [];
for (var i=0, length=this.cssRules.length; i < length; i++) {
cssTexts.push(this.cssRules[i].cssText);
}
return "@host {" + cssTexts.join("") + "}";
}
});
//.CommonJS
exports.CSSHostRule = CSSOM.CSSHostRule;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/CSSHostRule.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 246 |
```javascript
//.CommonJS
var CSSOM = {};
///CommonJS
/**
* @constructor
* @see path_to_url
*/
CSSOM.MatcherList = function MatcherList(){
this.length = 0;
};
CSSOM.MatcherList.prototype = {
constructor: CSSOM.MatcherList,
/**
* @return {string}
*/
get matcherText() {
return Array.prototype.join.call(this, ", ");
},
/**
* @param {string} value
*/
set matcherText(value) {
// just a temporary solution, actually it may be wrong by just split the value with ',', because a url can include ','.
var values = value.split(",");
var length = this.length = values.length;
for (var i=0; i<length; i++) {
this[i] = values[i].trim();
}
},
/**
* @param {string} matcher
*/
appendMatcher: function(matcher) {
if (Array.prototype.indexOf.call(this, matcher) === -1) {
this[this.length] = matcher;
this.length++;
}
},
/**
* @param {string} matcher
*/
deleteMatcher: function(matcher) {
var index = Array.prototype.indexOf.call(this, matcher);
if (index !== -1) {
Array.prototype.splice.call(this, index, 1);
}
}
};
//.CommonJS
exports.MatcherList = CSSOM.MatcherList;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/MatcherList.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 313 |
```javascript
//.CommonJS
var CSSOM = {
CSSRule: require("./CSSRule").CSSRule,
CSSStyleSheet: require("./CSSStyleSheet").CSSStyleSheet,
MediaList: require("./MediaList").MediaList
};
///CommonJS
/**
* @constructor
* @see path_to_url#cssimportrule
* @see path_to_url#CSS-CSSImportRule
*/
CSSOM.CSSImportRule = function CSSImportRule() {
CSSOM.CSSRule.call(this);
this.href = "";
this.media = new CSSOM.MediaList();
this.styleSheet = new CSSOM.CSSStyleSheet();
};
CSSOM.CSSImportRule.prototype = new CSSOM.CSSRule();
CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule;
CSSOM.CSSImportRule.prototype.type = 3;
Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", {
get: function() {
var mediaText = this.media.mediaText;
return "@import url(" + this.href + ")" + (mediaText ? " " + mediaText : "") + ";";
},
set: function(cssText) {
var i = 0;
/**
* @import url(partial.css) screen, handheld;
* || |
* after-import media
* |
* url
*/
var state = '';
var buffer = '';
var index;
for (var character; (character = cssText.charAt(i)); i++) {
switch (character) {
case ' ':
case '\t':
case '\r':
case '\n':
case '\f':
if (state === 'after-import') {
state = 'url';
} else {
buffer += character;
}
break;
case '@':
if (!state && cssText.indexOf('@import', i) === i) {
state = 'after-import';
i += 'import'.length;
buffer = '';
}
break;
case 'u':
if (state === 'url' && cssText.indexOf('url(', i) === i) {
index = cssText.indexOf(')', i + 1);
if (index === -1) {
throw i + ': ")" not found';
}
i += 'url('.length;
var url = cssText.slice(i, index);
if (url[0] === url[url.length - 1]) {
if (url[0] === '"' || url[0] === "'") {
url = url.slice(1, -1);
}
}
this.href = url;
i = index;
state = 'media';
}
break;
case '"':
if (state === 'url') {
index = cssText.indexOf('"', i + 1);
if (!index) {
throw i + ": '\"' not found";
}
this.href = cssText.slice(i + 1, index);
i = index;
state = 'media';
}
break;
case "'":
if (state === 'url') {
index = cssText.indexOf("'", i + 1);
if (!index) {
throw i + ': "\'" not found';
}
this.href = cssText.slice(i + 1, index);
i = index;
state = 'media';
}
break;
case ';':
if (state === 'media') {
if (buffer) {
this.media.mediaText = buffer.trim();
}
}
break;
default:
if (state === 'media') {
buffer += character;
}
break;
}
}
}
});
//.CommonJS
exports.CSSImportRule = CSSOM.CSSImportRule;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/CSSImportRule.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 795 |
```javascript
//.CommonJS
var CSSOM = {
CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration,
CSSRule: require("./CSSRule").CSSRule
};
///CommonJS
/**
* @constructor
* @see path_to_url#cssstylerule
* @see path_to_url#CSS-CSSStyleRule
*/
CSSOM.CSSStyleRule = function CSSStyleRule() {
CSSOM.CSSRule.call(this);
this.selectorText = "";
this.style = new CSSOM.CSSStyleDeclaration();
this.style.parentRule = this;
};
CSSOM.CSSStyleRule.prototype = new CSSOM.CSSRule();
CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule;
CSSOM.CSSStyleRule.prototype.type = 1;
Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", {
get: function() {
var text;
if (this.selectorText) {
text = this.selectorText + " {" + this.style.cssText + "}";
} else {
text = "";
}
return text;
},
set: function(cssText) {
var rule = CSSOM.CSSStyleRule.parse(cssText);
this.style = rule.style;
this.selectorText = rule.selectorText;
}
});
/**
* NON-STANDARD
* lightweight version of parse.js.
* @param {string} ruleText
* @return CSSStyleRule
*/
CSSOM.CSSStyleRule.parse = function(ruleText) {
var i = 0;
var state = "selector";
var index;
var j = i;
var buffer = "";
var SIGNIFICANT_WHITESPACE = {
"selector": true,
"value": true
};
var styleRule = new CSSOM.CSSStyleRule();
var name, priority="";
for (var character; (character = ruleText.charAt(i)); i++) {
switch (character) {
case " ":
case "\t":
case "\r":
case "\n":
case "\f":
if (SIGNIFICANT_WHITESPACE[state]) {
// Squash 2 or more white-spaces in the row into 1
switch (ruleText.charAt(i - 1)) {
case " ":
case "\t":
case "\r":
case "\n":
case "\f":
break;
default:
buffer += " ";
break;
}
}
break;
// String
case '"':
j = i + 1;
index = ruleText.indexOf('"', j) + 1;
if (!index) {
throw '" is missing';
}
buffer += ruleText.slice(i, index);
i = index - 1;
break;
case "'":
j = i + 1;
index = ruleText.indexOf("'", j) + 1;
if (!index) {
throw "' is missing";
}
buffer += ruleText.slice(i, index);
i = index - 1;
break;
// Comment
case "/":
if (ruleText.charAt(i + 1) === "*") {
i += 2;
index = ruleText.indexOf("*/", i);
if (index === -1) {
throw new SyntaxError("Missing */");
} else {
i = index + 1;
}
} else {
buffer += character;
}
break;
case "{":
if (state === "selector") {
styleRule.selectorText = buffer.trim();
buffer = "";
state = "name";
}
break;
case ":":
if (state === "name") {
name = buffer.trim();
buffer = "";
state = "value";
} else {
buffer += character;
}
break;
case "!":
if (state === "value" && ruleText.indexOf("!important", i) === i) {
priority = "important";
i += "important".length;
} else {
buffer += character;
}
break;
case ";":
if (state === "value") {
styleRule.style.setProperty(name, buffer.trim(), priority);
priority = "";
buffer = "";
state = "name";
} else {
buffer += character;
}
break;
case "}":
if (state === "value") {
styleRule.style.setProperty(name, buffer.trim(), priority);
priority = "";
buffer = "";
} else if (state === "name") {
break;
} else {
buffer += character;
}
state = "selector";
break;
default:
buffer += character;
break;
}
}
return styleRule;
};
//.CommonJS
exports.CSSStyleRule = CSSOM.CSSStyleRule;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/CSSStyleRule.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,031 |
```javascript
var CSSOM = {};
``` | /content/code_sandbox/node_modules/cssom/lib/CSSOM.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 7 |
```javascript
//.CommonJS
var CSSOM = {};
///CommonJS
/**
* @constructor
* @see path_to_url#the-stylesheet-interface
*/
CSSOM.StyleSheet = function StyleSheet() {
this.parentStyleSheet = null;
};
//.CommonJS
exports.StyleSheet = CSSOM.StyleSheet;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/StyleSheet.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 67 |
```javascript
//.CommonJS
var CSSOM = {
CSSValue: require('./CSSValue').CSSValue
};
///CommonJS
/**
* @constructor
* @see path_to_url
*
*/
CSSOM.CSSValueExpression = function CSSValueExpression(token, idx) {
this._token = token;
this._idx = idx;
};
CSSOM.CSSValueExpression.prototype = new CSSOM.CSSValue();
CSSOM.CSSValueExpression.prototype.constructor = CSSOM.CSSValueExpression;
/**
* parse css expression() value
*
* @return {Object}
* - error:
* or
* - idx:
* - expression:
*
* Example:
*
* .selector {
* zoom: expression(documentElement.clientWidth > 1000 ? '1000px' : 'auto');
* }
*/
CSSOM.CSSValueExpression.prototype.parse = function() {
var token = this._token,
idx = this._idx;
var character = '',
expression = '',
error = '',
info,
paren = [];
for (; ; ++idx) {
character = token.charAt(idx);
// end of token
if (character === '') {
error = 'css expression error: unfinished expression!';
break;
}
switch(character) {
case '(':
paren.push(character);
expression += character;
break;
case ')':
paren.pop(character);
expression += character;
break;
case '/':
if ((info = this._parseJSComment(token, idx))) { // comment?
if (info.error) {
error = 'css expression error: unfinished comment in expression!';
} else {
idx = info.idx;
// ignore the comment
}
} else if ((info = this._parseJSRexExp(token, idx))) { // regexp
idx = info.idx;
expression += info.text;
} else { // other
expression += character;
}
break;
case "'":
case '"':
info = this._parseJSString(token, idx, character);
if (info) { // string
idx = info.idx;
expression += info.text;
} else {
expression += character;
}
break;
default:
expression += character;
break;
}
if (error) {
break;
}
// end of expression
if (paren.length === 0) {
break;
}
}
var ret;
if (error) {
ret = {
error: error
};
} else {
ret = {
idx: idx,
expression: expression
};
}
return ret;
};
/**
*
* @return {Object|false}
* - idx:
* - text:
* or
* - error:
* or
* false
*
*/
CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) {
var nextChar = token.charAt(idx + 1),
text;
if (nextChar === '/' || nextChar === '*') {
var startIdx = idx,
endIdx,
commentEndChar;
if (nextChar === '/') { // line comment
commentEndChar = '\n';
} else if (nextChar === '*') { // block comment
commentEndChar = '*/';
}
endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1);
if (endIdx !== -1) {
endIdx = endIdx + commentEndChar.length - 1;
text = token.substring(idx, endIdx + 1);
return {
idx: endIdx,
text: text
};
} else {
var error = 'css expression error: unfinished comment in expression!';
return {
error: error
};
}
} else {
return false;
}
};
/**
*
* @return {Object|false}
* - idx:
* - text:
* or
* false
*
*/
CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) {
var endIdx = this._findMatchedIdx(token, idx, sep),
text;
if (endIdx === -1) {
return false;
} else {
text = token.substring(idx, endIdx + sep.length);
return {
idx: endIdx,
text: text
};
}
};
/**
* parse regexp in css expression
*
* @return {Object|false}
* - idx:
* - regExp:
* or
* false
*/
/*
all legal RegExp
/a/
(/a/)
[/a/]
[12, /a/]
!/a/
+/a/
-/a/
* /a/
/ /a/
%/a/
===/a/
!==/a/
==/a/
!=/a/
>/a/
>=/a/
</a/
<=/a/
&/a/
|/a/
^/a/
~/a/
<</a/
>>/a/
>>>/a/
&&/a/
||/a/
?/a/
=/a/
,/a/
delete /a/
in /a/
instanceof /a/
new /a/
typeof /a/
void /a/
*/
CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) {
var before = token.substring(0, idx).replace(/\s+$/, ""),
legalRegx = [
/^$/,
/\($/,
/\[$/,
/\!$/,
/\+$/,
/\-$/,
/\*$/,
/\/\s+/,
/\%$/,
/\=$/,
/\>$/,
/<$/,
/\&$/,
/\|$/,
/\^$/,
/\~$/,
/\?$/,
/\,$/,
/delete$/,
/in$/,
/instanceof$/,
/new$/,
/typeof$/,
/void$/
];
var isLegal = legalRegx.some(function(reg) {
return reg.test(before);
});
if (!isLegal) {
return false;
} else {
var sep = '/';
// same logic as string
return this._parseJSString(token, idx, sep);
}
};
/**
*
* find next sep(same line) index in `token`
*
* @return {Number}
*
*/
CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) {
var startIdx = idx,
endIdx;
var NOT_FOUND = -1;
while(true) {
endIdx = token.indexOf(sep, startIdx + 1);
if (endIdx === -1) { // not found
endIdx = NOT_FOUND;
break;
} else {
var text = token.substring(idx + 1, endIdx),
matched = text.match(/\\+$/);
if (!matched || matched[0] % 2 === 0) { // not escaped
break;
} else {
startIdx = endIdx;
}
}
}
// boundary must be in the same line(js sting or regexp)
var nextNewLineIdx = token.indexOf('\n', idx + 1);
if (nextNewLineIdx < endIdx) {
endIdx = NOT_FOUND;
}
return endIdx;
};
//.CommonJS
exports.CSSValueExpression = CSSOM.CSSValueExpression;
///CommonJS
``` | /content/code_sandbox/node_modules/cssom/lib/CSSValueExpression.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,635 |
```javascript
'use strict'
var net = require('net')
, tls = require('tls')
, http = require('http')
, https = require('https')
, events = require('events')
, assert = require('assert')
, util = require('util')
, Buffer = require('safe-buffer').Buffer
;
exports.httpOverHttp = httpOverHttp
exports.httpsOverHttp = httpsOverHttp
exports.httpOverHttps = httpOverHttps
exports.httpsOverHttps = httpsOverHttps
function httpOverHttp(options) {
var agent = new TunnelingAgent(options)
agent.request = http.request
return agent
}
function httpsOverHttp(options) {
var agent = new TunnelingAgent(options)
agent.request = http.request
agent.createSocket = createSecureSocket
agent.defaultPort = 443
return agent
}
function httpOverHttps(options) {
var agent = new TunnelingAgent(options)
agent.request = https.request
return agent
}
function httpsOverHttps(options) {
var agent = new TunnelingAgent(options)
agent.request = https.request
agent.createSocket = createSecureSocket
agent.defaultPort = 443
return agent
}
function TunnelingAgent(options) {
var self = this
self.options = options || {}
self.proxyOptions = self.options.proxy || {}
self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets
self.requests = []
self.sockets = []
self.on('free', function onFree(socket, host, port) {
for (var i = 0, len = self.requests.length; i < len; ++i) {
var pending = self.requests[i]
if (pending.host === host && pending.port === port) {
// Detect the request to connect same origin server,
// reuse the connection.
self.requests.splice(i, 1)
pending.request.onSocket(socket)
return
}
}
socket.destroy()
self.removeSocket(socket)
})
}
util.inherits(TunnelingAgent, events.EventEmitter)
TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
var self = this
// Legacy API: addRequest(req, host, port, path)
if (typeof options === 'string') {
options = {
host: options,
port: arguments[2],
path: arguments[3]
};
}
if (self.sockets.length >= this.maxSockets) {
// We are over limit so we'll add it to the queue.
self.requests.push({host: options.host, port: options.port, request: req})
return
}
// If we are under maxSockets create a new one.
self.createConnection({host: options.host, port: options.port, request: req})
}
TunnelingAgent.prototype.createConnection = function createConnection(pending) {
var self = this
self.createSocket(pending, function(socket) {
socket.on('free', onFree)
socket.on('close', onCloseOrRemove)
socket.on('agentRemove', onCloseOrRemove)
pending.request.onSocket(socket)
function onFree() {
self.emit('free', socket, pending.host, pending.port)
}
function onCloseOrRemove(err) {
self.removeSocket(socket)
socket.removeListener('free', onFree)
socket.removeListener('close', onCloseOrRemove)
socket.removeListener('agentRemove', onCloseOrRemove)
}
})
}
TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
var self = this
var placeholder = {}
self.sockets.push(placeholder)
var connectOptions = mergeOptions({}, self.proxyOptions,
{ method: 'CONNECT'
, path: options.host + ':' + options.port
, agent: false
}
)
if (connectOptions.proxyAuth) {
connectOptions.headers = connectOptions.headers || {}
connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
Buffer.from(connectOptions.proxyAuth).toString('base64')
}
debug('making CONNECT request')
var connectReq = self.request(connectOptions)
connectReq.useChunkedEncodingByDefault = false // for v0.6
connectReq.once('response', onResponse) // for v0.6
connectReq.once('upgrade', onUpgrade) // for v0.6
connectReq.once('connect', onConnect) // for v0.7 or later
connectReq.once('error', onError)
connectReq.end()
function onResponse(res) {
// Very hacky. This is necessary to avoid http-parser leaks.
res.upgrade = true
}
function onUpgrade(res, socket, head) {
// Hacky.
process.nextTick(function() {
onConnect(res, socket, head)
})
}
function onConnect(res, socket, head) {
connectReq.removeAllListeners()
socket.removeAllListeners()
if (res.statusCode === 200) {
assert.equal(head.length, 0)
debug('tunneling connection has established')
self.sockets[self.sockets.indexOf(placeholder)] = socket
cb(socket)
} else {
debug('tunneling socket could not be established, statusCode=%d', res.statusCode)
var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)
error.code = 'ECONNRESET'
options.request.emit('error', error)
self.removeSocket(placeholder)
}
}
function onError(cause) {
connectReq.removeAllListeners()
debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack)
var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)
error.code = 'ECONNRESET'
options.request.emit('error', error)
self.removeSocket(placeholder)
}
}
TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
var pos = this.sockets.indexOf(socket)
if (pos === -1) return
this.sockets.splice(pos, 1)
var pending = this.requests.shift()
if (pending) {
// If we have pending requests and a socket gets closed a new one
// needs to be created to take over in the pool for the one that closed.
this.createConnection(pending)
}
}
function createSecureSocket(options, cb) {
var self = this
TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
// 0 is dummy port for v0.6
var secureSocket = tls.connect(0, mergeOptions({}, self.options,
{ servername: options.host
, socket: socket
}
))
self.sockets[self.sockets.indexOf(socket)] = secureSocket
cb(secureSocket)
})
}
function mergeOptions(target) {
for (var i = 1, len = arguments.length; i < len; ++i) {
var overrides = arguments[i]
if (typeof overrides === 'object') {
var keys = Object.keys(overrides)
for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
var k = keys[j]
if (overrides[k] !== undefined) {
target[k] = overrides[k]
}
}
}
}
return target
}
var debug
if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
debug = function() {
var args = Array.prototype.slice.call(arguments)
if (typeof args[0] === 'string') {
args[0] = 'TUNNEL: ' + args[0]
} else {
args.unshift('TUNNEL:')
}
console.error.apply(console, args)
}
} else {
debug = function() {}
}
exports.debug = debug // for test
``` | /content/code_sandbox/node_modules/tunnel-agent/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,705 |
```javascript
/*
* All rights reserved.
*
* nwmatcher-noqsa.js - A fast CSS selector engine and matcher
*
* Author: Diego Perini <diego.perini at gmail com>
* Version: 1.4.4
* Created: 20070722
* Release: 20180305
*
* path_to_url
* Download:
* path_to_url
*/
(function(global, factory) {
if (typeof module == 'object' && typeof exports == 'object') {
module.exports = factory;
} else if (typeof define === 'function' && define["amd"]) {
define(factory);
} else {
global.NW || (global.NW = { });
global.NW.Dom = factory(global);
}
})(this, function(global) {
var version = 'nwmatcher-1.4.4',
doc = global.document,
root = doc.documentElement,
isSingleMatch,
isSingleSelect,
lastSlice,
lastContext,
lastPosition,
lastMatcher,
lastSelector,
lastPartsMatch,
lastPartsSelect,
prefixes = '(?:[#.:]|::)?',
operators = '([~*^$|!]?={1})',
whitespace = '[\\x20\\t\\n\\r\\f]',
combinators = '\\x20|[>+~](?=[^>+~])',
pseudoparms = '(?:[-+]?\\d*n)?[-+]?\\d*',
skip_groups = '\\[.*\\]|\\(.*\\)|\\{.*\\}',
any_esc_chr = '\\\\.',
alphalodash = '[_a-zA-Z]',
non_asc_chr = '[^\\x00-\\x9f]',
escaped_chr = '\\\\[^\\n\\r\\f0-9a-fA-F]',
unicode_chr = '\\\\[0-9a-fA-F]{1,6}(?:\\r\\n|' + whitespace + ')?',
quotedvalue = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"' + "|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'",
reSplitGroup = /([^,\\()[\]]+|\[[^[\]]*\]|\[.*\]|\([^()]+\)|\(.*\)|\{[^{}]+\}|\{.*\}|\\.)+/g,
reTrimSpaces = RegExp('[\\n\\r\\f]|^' + whitespace + '+|' + whitespace + '+$', 'g'),
reEscapedChars = /\\([0-9a-fA-F]{1,6}[\x20\t\n\r\f]?|.)|([\x22\x27])/g,
standardValidator, extendedValidator, reValidator,
attrcheck, attributes, attrmatcher, pseudoclass,
reOptimizeSelector, reSimpleNot, reSplitToken,
Optimize, identifier, extensions = '.+',
Patterns = {
spseudos: /^\:(root|empty|(?:first|last|only)(?:-child|-of-type)|nth(?:-last)?(?:-child|-of-type)\(\s?(even|odd|(?:[-+]{0,1}\d*n\s?)?[-+]{0,1}\s?\d*)\s?\))?(.*)/i,
dpseudos: /^\:(link|visited|target|active|focus|hover|checked|disabled|enabled|selected|lang\(([-\w]{2,})\)|(?:matches|not)\(\s?(:nth(?:-last)?(?:-child|-of-type)\(\s?(?:even|odd|(?:[-+]{0,1}\d*n\s?)?[-+]{0,1}\s?\d*)\s?\)|[^()]*)\s?\))?(.*)/i,
epseudos: /^((?:[:]{1,2}(?:after|before|first-letter|first-line))|(?:[:]{2,2}(?:selection|backdrop|placeholder)))?(.*)/i,
children: RegExp('^' + whitespace + '?\\>' + whitespace + '?(.*)'),
adjacent: RegExp('^' + whitespace + '?\\+' + whitespace + '?(.*)'),
relative: RegExp('^' + whitespace + '?\\~' + whitespace + '?(.*)'),
ancestor: RegExp('^' + whitespace + '+(.*)'),
universal: RegExp('^\\*(.*)')
},
Tokens = {
prefixes: prefixes,
identifier: identifier,
attributes: attributes
},
QUIRKS_MODE,
XML_DOCUMENT,
GEBTN = 'getElementsByTagName' in doc,
GEBCN = 'getElementsByClassName' in doc,
IE_LT_9 = typeof doc.addEventListener != 'function',
LINK_NODES = { a: 1, A: 1, area: 1, AREA: 1, link: 1, LINK: 1 },
ATTR_BOOLEAN = {
checked: 1, disabled: 1, ismap: 1,
multiple: 1, readonly: 1, selected: 1
},
ATTR_DEFAULT = {
value: 'defaultValue',
checked: 'defaultChecked',
selected: 'defaultSelected'
},
ATTR_URIDATA = {
action: 2, cite: 2, codebase: 2, data: 2, href: 2,
longdesc: 2, lowsrc: 2, src: 2, usemap: 2
},
HTML_TABLE = {
'accept': 1, 'accept-charset': 1, 'align': 1, 'alink': 1, 'axis': 1,
'bgcolor': 1, 'charset': 1, 'checked': 1, 'clear': 1, 'codetype': 1, 'color': 1,
'compact': 1, 'declare': 1, 'defer': 1, 'dir': 1, 'direction': 1, 'disabled': 1,
'enctype': 1, 'face': 1, 'frame': 1, 'hreflang': 1, 'http-equiv': 1, 'lang': 1,
'language': 1, 'link': 1, 'media': 1, 'method': 1, 'multiple': 1, 'nohref': 1,
'noresize': 1, 'noshade': 1, 'nowrap': 1, 'readonly': 1, 'rel': 1, 'rev': 1,
'rules': 1, 'scope': 1, 'scrolling': 1, 'selected': 1, 'shape': 1, 'target': 1,
'text': 1, 'type': 1, 'valign': 1, 'valuetype': 1, 'vlink': 1
},
NATIVE_TRAVERSAL_API =
'nextElementSibling' in root &&
'previousElementSibling' in root,
Selectors = { },
Operators = {
'=': "n=='%m'",
'^=': "n.indexOf('%m')==0",
'*=': "n.indexOf('%m')>-1",
'|=': "(n+'-').indexOf('%m-')==0",
'~=': "(' '+n+' ').indexOf(' %m ')>-1",
'$=': "n.substr(n.length-'%m'.length)=='%m'"
},
concatCall =
function(data, elements, callback) {
var i = -1, element;
while ((element = elements[++i])) {
if (false === callback(data[data.length] = element)) { break; }
}
return data;
},
switchContext =
function(from, force) {
var oldDoc = doc;
lastContext = from;
doc = from.ownerDocument || from;
if (force || oldDoc !== doc) {
root = doc.documentElement;
XML_DOCUMENT = doc.createElement('DiV').nodeName == 'DiV';
QUIRKS_MODE = !XML_DOCUMENT &&
typeof doc.compatMode == 'string' ?
doc.compatMode.indexOf('CSS') < 0 :
(function() {
var style = doc.createElement('div').style;
return style && (style.width = 1) && style.width == '1px';
})();
Config.CACHING && Dom.setCache(true, doc);
}
},
codePointToUTF16 =
function(codePoint) {
if (codePoint < 1 || codePoint > 0x10ffff ||
(codePoint > 0xd7ff && codePoint < 0xe000)) {
return '\\ufffd';
}
if (codePoint < 0x10000) {
var lowHex = '000' + codePoint.toString(16);
return '\\u' + lowHex.substr(lowHex.length - 4);
}
return '\\u' + (((codePoint - 0x10000) >> 0x0a) + 0xd800).toString(16) +
'\\u' + (((codePoint - 0x10000) % 0x400) + 0xdc00).toString(16);
},
stringFromCodePoint =
function(codePoint) {
if (codePoint < 1 || codePoint > 0x10ffff ||
(codePoint > 0xd7ff && codePoint < 0xe000)) {
return '\ufffd';
}
if (codePoint < 0x10000) {
return String.fromCharCode(codePoint);
}
return String.fromCodePoint ?
String.fromCodePoint(codePoint) :
String.fromCharCode(
((codePoint - 0x10000) >> 0x0a) + 0xd800,
((codePoint - 0x10000) % 0x400) + 0xdc00);
},
convertEscapes =
function(str) {
return str.replace(reEscapedChars,
function(substring, p1, p2) {
return p2 ? '\\' + p2 :
(/^[0-9a-fA-F]/).test(p1) ? codePointToUTF16(parseInt(p1, 16)) :
(/^[\\\x22\x27]/).test(p1) ? substring :
p1;
}
);
},
unescapeIdentifier =
function(str) {
return str.replace(reEscapedChars,
function(substring, p1, p2) {
return p2 ? p2 :
(/^[0-9a-fA-F]/).test(p1) ? stringFromCodePoint(parseInt(p1, 16)) :
(/^[\\\x22\x27]/).test(p1) ? substring :
p1;
}
);
},
byIdRaw =
function(id, elements) {
var i = -1, element;
while ((element = elements[++i])) {
if (element.getAttribute('id') == id) {
break;
}
}
return element || null;
},
_byId = !IE_LT_9 ?
function(id, from) {
id = (/\\/).test(id) ? unescapeIdentifier(id) : id;
return from.getElementById && from.getElementById(id) ||
byIdRaw(id, from.getElementsByTagName('*'));
} :
function(id, from) {
var element = null;
id = (/\\/).test(id) ? unescapeIdentifier(id) : id;
if (XML_DOCUMENT || from.nodeType != 9) {
return byIdRaw(id, from.getElementsByTagName('*'));
}
if ((element = from.getElementById(id)) &&
element.name == id && from.getElementsByName) {
return byIdRaw(id, from.getElementsByName(id));
}
return element;
},
byId =
function(id, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byId(id, from);
},
byTagRaw =
function(tag, from) {
var any = tag == '*', element = from, elements = [ ], next = element.firstChild;
any || (tag = tag.toUpperCase());
while ((element = next)) {
if (element.tagName > '@' && (any || element.tagName.toUpperCase() == tag)) {
elements[elements.length] = element;
}
if ((next = element.firstChild || element.nextSibling)) continue;
while (!next && (element = element.parentNode) && element !== from) {
next = element.nextSibling;
}
}
return elements;
},
contains = 'compareDocumentPosition' in root ?
function(container, element) {
return (container.compareDocumentPosition(element) & 16) == 16;
} : 'contains' in root ?
function(container, element) {
return container !== element && container.contains(element);
} :
function(container, element) {
while ((element = element.parentNode)) {
if (element === container) return true;
}
return false;
},
getAttribute = !IE_LT_9 ?
function(node, attribute) {
return node.getAttribute(attribute);
} :
function(node, attribute) {
attribute = attribute.toLowerCase();
if (typeof node[attribute] == 'object') {
return node.attributes[attribute] &&
node.attributes[attribute].value;
}
return (
attribute == 'type' ? node.getAttribute(attribute) :
ATTR_URIDATA[attribute] ? node.getAttribute(attribute, 2) :
ATTR_BOOLEAN[attribute] ? node.getAttribute(attribute) ? attribute : 'false' :
(node = node.getAttributeNode(attribute)) && node.value);
},
hasAttribute = !IE_LT_9 && root.hasAttribute ?
function(node, attribute) {
return node.hasAttribute(attribute);
} :
function(node, attribute) {
var obj = node.getAttributeNode(attribute = attribute.toLowerCase());
return ATTR_DEFAULT[attribute] && attribute != 'value' ?
node[ATTR_DEFAULT[attribute]] : obj && obj.specified;
},
isEmpty =
function(node) {
node = node.firstChild;
while (node) {
if (node.nodeType == 3 || node.nodeName > '@') return false;
node = node.nextSibling;
}
return true;
},
isLink =
function(element) {
return hasAttribute(element, 'href') && LINK_NODES[element.nodeName];
},
nthElement =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling';
while ((element = element[succ])) {
if (element.nodeName > '@') ++count;
}
return count;
},
nthOfType =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling', type = element.nodeName;
while ((element = element[succ])) {
if (element.nodeName == type) ++count;
}
return count;
},
configure =
function(option) {
if (typeof option == 'string') { return !!Config[option]; }
if (typeof option != 'object') { return Config; }
for (var i in option) {
Config[i] = !!option[i];
if (i == 'SIMPLENOT') {
matchContexts = { };
matchResolvers = { };
selectContexts = { };
selectResolvers = { };
}
}
setIdentifierSyntax();
reValidator = RegExp(Config.SIMPLENOT ?
standardValidator : extendedValidator);
return true;
},
emit =
function(message) {
if (Config.VERBOSITY) { throw Error(message); }
if (Config.LOGERRORS && console && console.log) {
console.log(message);
}
},
Config = {
CACHING: false,
ESCAPECHR: true,
NON_ASCII: true,
SELECTOR3: true,
UNICODE16: true,
SHORTCUTS: false,
SIMPLENOT: true,
SVG_LCASE: false,
UNIQUE_ID: true,
USE_HTML5: true,
VERBOSITY: true,
LOGERRORS: true
},
initialize =
function(doc) {
setIdentifierSyntax();
switchContext(doc, true);
},
setIdentifierSyntax =
function() {
var syntax = '', start = Config['SELECTOR3'] ? '-{2}|' : '';
Config['NON_ASCII'] && (syntax += '|' + non_asc_chr);
Config['UNICODE16'] && (syntax += '|' + unicode_chr);
Config['ESCAPECHR'] && (syntax += '|' + escaped_chr);
syntax += (Config['UNICODE16'] || Config['ESCAPECHR']) ? '' : '|' + any_esc_chr;
identifier = '-?(?:' + start + alphalodash + syntax + ')(?:-|[0-9]|' + alphalodash + syntax + ')*';
attrcheck = '(' + quotedvalue + '|' + identifier + ')';
attributes = whitespace + '*(' + identifier + '(?::' + identifier + ')?)' +
whitespace + '*(?:' + operators + whitespace + '*' + attrcheck + ')?' + whitespace + '*' + '(i)?' + whitespace + '*';
attrmatcher = attributes.replace(attrcheck, '([\\x22\\x27]*)((?:\\\\?.)*?)\\3');
pseudoclass = '((?:' +
pseudoparms + '|' + quotedvalue + '|' +
prefixes + identifier + '|' +
'\\[' + attributes + '\\]|' +
'\\(.+\\)|' + whitespace + '*|' +
',)+)';
standardValidator =
'(?=[\\x20\\t\\n\\r\\f]*[^>+~(){}<>])' +
'(' +
'\\*' +
'|(?:' + prefixes + identifier + ')' +
'|' + combinators +
'|\\[' + attributes + '\\]' +
'|\\(' + pseudoclass + '\\)' +
'|\\{' + extensions + '\\}' +
'|(?:,|' + whitespace + '*)' +
')+';
reSimpleNot = RegExp('^(' +
'(?!:not)' +
'(' + prefixes + identifier +
'|\\([^()]*\\))+' +
'|\\[' + attributes + '\\]' +
')$');
reSplitToken = RegExp('(' +
prefixes + identifier + '|' +
'\\[' + attributes + '\\]|' +
'\\(' + pseudoclass + '\\)|' +
'\\\\.|[^\\x20\\t\\n\\r\\f>+~])+', 'g');
reOptimizeSelector = RegExp(identifier + '|^$');
Optimize = {
ID: RegExp('^\\*?#(' + identifier + ')|' + skip_groups),
TAG: RegExp('^(' + identifier + ')|' + skip_groups),
CLASS: RegExp('^\\.(' + identifier + '$)|' + skip_groups)
};
Patterns.id = RegExp('^#(' + identifier + ')(.*)');
Patterns.tagName = RegExp('^(' + identifier + ')(.*)');
Patterns.className = RegExp('^\\.(' + identifier + ')(.*)');
Patterns.attribute = RegExp('^\\[' + attrmatcher + '\\](.*)');
Tokens.identifier = identifier;
Tokens.attributes = attributes;
extendedValidator = standardValidator.replace(pseudoclass, '.*');
reValidator = RegExp(standardValidator);
},
ACCEPT_NODE = 'r[r.length]=c[k];if(f&&false===f(c[k]))break main;else continue main;',
REJECT_NODE = IE_LT_9 ? 'if(e.nodeName<"A")continue;' : '',
TO_UPPER_CASE = IE_LT_9 ? '.toUpperCase()' : '',
compile =
function(selector, source, mode) {
var parts = typeof selector == 'string' ? selector.match(reSplitGroup) : selector;
typeof source == 'string' || (source = '');
if (parts.length == 1) {
source += compileSelector(parts[0], mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
} else {
var i = -1, seen = { }, token;
while ((token = parts[++i])) {
token = token.replace(reTrimSpaces, '');
if (!seen[token] && (seen[token] = true)) {
source += compileSelector(token, mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
}
}
}
if (mode) {
return Function('c,s,d,h,g,f',
'var N,n,x=0,k=-1,e,r=[];main:while((e=c[++k])){' + source + '}return r;');
} else {
return Function('e,s,d,h,g,f',
'var N,n,x=0,k=e;' + source + 'return false;');
}
},
compileSelector =
function(selector, source, mode) {
var a, b, n, k = 0, expr, match, result, status, test, type;
while (selector) {
k++;
if ((match = selector.match(Patterns.universal))) {
expr = '';
}
else if ((match = selector.match(Patterns.id))) {
match[1] = (/\\/).test(match[1]) ? convertEscapes(match[1]) : match[1];
source = 'if(' + (XML_DOCUMENT ?
's.getAttribute(e,"id")' :
'(e.submit?s.getAttribute(e,"id"):e.id)') +
'=="' + match[1] + '"' +
'){' + source + '}';
}
else if ((match = selector.match(Patterns.tagName))) {
test = Config.SVG_LCASE ? '||e.nodeName=="' + match[1].toLowerCase() + '"' : '';
source = 'if(e.nodeName' + (XML_DOCUMENT ?
'=="' + match[1] + '"' : TO_UPPER_CASE +
'=="' + match[1].toUpperCase() + '"' + test) +
'){' + source + '}';
}
else if ((match = selector.match(Patterns.className))) {
match[1] = (/\\/).test(match[1]) ? convertEscapes(match[1]) : match[1];
match[1] = QUIRKS_MODE ? match[1].toLowerCase() : match[1];
source = 'if((n=' + (XML_DOCUMENT ?
'e.getAttribute("class")' : 'e.className') +
')&&n.length&&(" "+' + (QUIRKS_MODE ? 'n.toLowerCase()' : 'n') +
'.replace(/' + whitespace + '+/g," ")+" ").indexOf(" ' + match[1] + ' ")>-1' +
'){' + source + '}';
}
else if ((match = selector.match(Patterns.attribute))) {
expr = match[1].split(':');
expr = expr.length == 2 ? expr[1] : expr[0] + '';
if (match[2] && !Operators[match[2]]) {
emit('Unsupported operator in attribute selectors "' + selector + '"');
return '';
}
test = 'false';
if (match[2] && match[4] && (test = Operators[match[2]])) {
match[4] = (/\\/).test(match[4]) ? convertEscapes(match[4]) : match[4];
type = match[5] == 'i' || HTML_TABLE[expr.toLowerCase()];
test = test.replace(/\%m/g, type ? match[4].toLowerCase() : match[4]);
} else if (match[2] == '!=' || match[2] == '=') {
test = 'n' + match[2] + '=""';
}
source = 'if(n=s.hasAttribute(e,"' + match[1] + '")){' +
(match[2] ? 'n=s.getAttribute(e,"' + match[1] + '")' : '') +
(type && match[2] ? '.toLowerCase();' : ';') +
'if(' + (match[2] ? test : 'n') + '){' + source + '}}';
}
else if ((match = selector.match(Patterns.adjacent))) {
source = NATIVE_TRAVERSAL_API ?
'var N' + k + '=e;if((e=e.previousElementSibling)){' + source + '}e=N' + k + ';' :
'var N' + k + '=e;while((e=e.previousSibling)){if(e.nodeType==1){' + source + 'break;}}e=N' + k + ';';
}
else if ((match = selector.match(Patterns.relative))) {
source = NATIVE_TRAVERSAL_API ?
'var N' + k + '=e;while((e=e.previousElementSibling)){' + source + '}e=N' + k + ';' :
'var N' + k + '=e;while((e=e.previousSibling)){if(e.nodeType==1){' + source + '}}e=N' + k + ';';
}
else if ((match = selector.match(Patterns.children))) {
source = 'var N' + k + '=e;if((e=e.parentNode)&&e.nodeType==1){' + source + '}e=N' + k + ';';
}
else if ((match = selector.match(Patterns.ancestor))) {
source = 'var N' + k + '=e;while((e=e.parentNode)&&e.nodeType==1){' + source + '}e=N' + k + ';';
}
else if ((match = selector.match(Patterns.spseudos)) && match[1]) {
switch (match[1]) {
case 'root':
if (match[3]) {
source = 'if(e===h||s.contains(h,e)){' + source + '}';
} else {
source = 'if(e===h){' + source + '}';
}
break;
case 'empty':
source = 'if(s.isEmpty(e)){' + source + '}';
break;
default:
if (match[1] && match[2]) {
if (match[2] == 'n') {
source = 'if(e!==h){' + source + '}';
break;
} else if (match[2] == 'even') {
a = 2;
b = 0;
} else if (match[2] == 'odd') {
a = 2;
b = 1;
} else {
b = ((n = match[2].match(/(-?\d+)$/)) ? parseInt(n[1], 10) : 0);
a = ((n = match[2].match(/(-?\d*)n/i)) ? parseInt(n[1], 10) : 0);
if (n && n[1] == '-') a = -1;
}
test = a > 1 ?
(/last/i.test(match[1])) ? '(n-(' + b + '))%' + a + '==0' :
'n>=' + b + '&&(n-(' + b + '))%' + a + '==0' : a < -1 ?
(/last/i.test(match[1])) ? '(n-(' + b + '))%' + a + '==0' :
'n<=' + b + '&&(n-(' + b + '))%' + a + '==0' : a === 0 ?
'n==' + b : a == -1 ? 'n<=' + b : 'n>=' + b;
source =
'if(e!==h){' +
'n=s[' + (/-of-type/i.test(match[1]) ? '"nthOfType"' : '"nthElement"') + ']' +
'(e,' + (/last/i.test(match[1]) ? 'true' : 'false') + ');' +
'if(' + test + '){' + source + '}' +
'}';
} else {
a = /first/i.test(match[1]) ? 'previous' : 'next';
n = /only/i.test(match[1]) ? 'previous' : 'next';
b = /first|last/i.test(match[1]);
type = /-of-type/i.test(match[1]) ? '&&n.nodeName!=e.nodeName' : '&&n.nodeName<"@"';
source = 'if(e!==h){' +
( 'n=e;while((n=n.' + a + 'Sibling)' + type + ');if(!n){' + (b ? source :
'n=e;while((n=n.' + n + 'Sibling)' + type + ');if(!n){' + source + '}') + '}' ) + '}';
}
break;
}
}
else if ((match = selector.match(Patterns.dpseudos)) && match[1]) {
switch (match[1].match(/^\w+/)[0]) {
case 'matches':
expr = match[3].replace(reTrimSpaces, '');
source = 'if(s.match(e, "' + expr.replace(/\x22/g, '\\"') + '",g)){' + source +'}';
break;
case 'not':
expr = match[3].replace(reTrimSpaces, '');
if (Config.SIMPLENOT && !reSimpleNot.test(expr)) {
emit('Negation pseudo-class only accepts simple selectors "' + selector + '"');
return '';
} else {
if ('compatMode' in doc) {
source = 'if(!' + compile(expr, '', false) + '(e,s,d,h,g)){' + source + '}';
} else {
source = 'if(!s.match(e, "' + expr.replace(/\x22/g, '\\"') + '",g)){' + source +'}';
}
}
break;
case 'checked':
source = 'if((typeof e.form!=="undefined"&&(/^(?:radio|checkbox)$/i).test(e.type)&&e.checked)' +
(Config.USE_HTML5 ? '||(/^option$/i.test(e.nodeName)&&(e.selected||e.checked))' : '') +
'){' + source + '}';
break;
case 'disabled':
source = 'if(((typeof e.form!=="undefined"' +
(Config.USE_HTML5 ? '' : '&&!(/^hidden$/i).test(e.type)') +
')||s.isLink(e))&&e.disabled===true){' + source + '}';
break;
case 'enabled':
source = 'if(((typeof e.form!=="undefined"' +
(Config.USE_HTML5 ? '' : '&&!(/^hidden$/i).test(e.type)') +
')||s.isLink(e))&&e.disabled===false){' + source + '}';
break;
case 'lang':
test = '';
if (match[2]) test = match[2].substr(0, 2) + '-';
source = 'do{(n=e.lang||"").toLowerCase();' +
'if((n==""&&h.lang=="' + match[2].toLowerCase() + '")||' +
'(n&&(n=="' + match[2].toLowerCase() +
'"||n.substr(0,3)=="' + test.toLowerCase() + '")))' +
'{' + source + 'break;}}while((e=e.parentNode)&&e!==g);';
break;
case 'target':
source = 'if(e.id==d.location.hash.slice(1)){' + source + '}';
break;
case 'link':
source = 'if(s.isLink(e)&&!e.visited){' + source + '}';
break;
case 'visited':
source = 'if(s.isLink(e)&&e.visited){' + source + '}';
break;
case 'active':
source = 'if(e===d.activeElement){' + source + '}';
break;
case 'hover':
source = 'if(e===d.hoverElement){' + source + '}';
break;
case 'focus':
source = 'hasFocus' in doc ?
'if(e===d.activeElement&&d.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number")){' + source + '}' :
'if(e===d.activeElement&&(e.type||e.href)){' + source + '}';
break;
case 'selected':
source = 'if(/^option$/i.test(e.nodeName)&&(e.selected||e.checked)){' + source + '}';
break;
default:
break;
}
}
else if ((match = selector.match(Patterns.epseudos)) && match[1]) {
source = 'if(!(/1|11/).test(e.nodeType)){' + source + '}';
}
else {
expr = false;
status = false;
for (expr in Selectors) {
if ((match = selector.match(Selectors[expr].Expression)) && match[1]) {
result = Selectors[expr].Callback(match, source);
if ('match' in result) { match = result.match; }
source = result.source;
status = result.status;
if (status) { break; }
}
}
if (!status) {
emit('Unknown pseudo-class selector "' + selector + '"');
return '';
}
if (!expr) {
emit('Unknown token in selector "' + selector + '"');
return '';
}
}
if (!match) {
emit('Invalid syntax in selector "' + selector + '"');
return '';
}
selector = match && match[match.length - 1];
}
return source;
},
match =
function(element, selector, from, callback) {
var parts;
if (!(element && element.nodeType == 1)) {
emit('Invalid element argument');
return false;
} else if (typeof selector != 'string') {
emit('Invalid selector argument');
return false;
} else if (lastContext !== from) {
switchContext(from || (from = element.ownerDocument));
}
selector = selector.
replace(reTrimSpaces, '').
replace(/\x00|\\$/g, '\ufffd');
Config.SHORTCUTS && (selector = Dom.shortcuts(selector, element, from));
if (lastMatcher != selector) {
if ((parts = selector.match(reValidator)) && parts[0] == selector) {
isSingleMatch = (parts = selector.match(reSplitGroup)).length < 2;
lastMatcher = selector;
lastPartsMatch = parts;
} else {
emit('The string "' + selector + '", is not a valid CSS selector');
return false;
}
} else parts = lastPartsMatch;
if (!matchResolvers[selector] || matchContexts[selector] !== from) {
matchResolvers[selector] = compile(isSingleMatch ? [selector] : parts, '', false);
matchContexts[selector] = from;
}
return matchResolvers[selector](element, Snapshot, doc, root, from, callback);
},
first =
function(selector, from) {
return select(selector, from, function() { return false; })[0] || null;
},
select =
function(selector, from, callback) {
var i, changed, element, elements, parts, token, original = selector;
if (arguments.length === 0) {
emit('Not enough arguments');
return [ ];
} else if (typeof selector != 'string') {
return [ ];
} else if (from && !(/1|9|11/).test(from.nodeType)) {
emit('Invalid or illegal context element');
return [ ];
} else if (lastContext !== from) {
switchContext(from || (from = doc));
}
if (Config.CACHING && (elements = Dom.loadResults(original, from, doc, root))) {
return callback ? concatCall([ ], elements, callback) : elements;
}
selector = selector.
replace(reTrimSpaces, '').
replace(/\x00|\\$/g, '\ufffd');
Config.SHORTCUTS && (selector = Dom.shortcuts(selector, from));
if ((changed = lastSelector != selector)) {
if ((parts = selector.match(reValidator)) && parts[0] == selector) {
isSingleSelect = (parts = selector.match(reSplitGroup)).length < 2;
lastSelector = selector;
lastPartsSelect = parts;
} else {
emit('The string "' + selector + '", is not a valid CSS selector');
return [ ];
}
} else parts = lastPartsSelect;
if (from.nodeType == 11) {
elements = byTagRaw('*', from);
} else if (isSingleSelect) {
if (changed) {
parts = selector.match(reSplitToken);
token = parts[parts.length - 1];
lastSlice = token.split(':not');
lastSlice = lastSlice[lastSlice.length - 1];
lastPosition = selector.length - token.length;
}
if (Config.UNIQUE_ID && lastSlice && (parts = lastSlice.match(Optimize.ID)) && (token = parts[1])) {
if ((element = _byId(token, from))) {
if (match(element, selector)) {
callback && callback(element);
elements = [element];
} else elements = [ ];
}
}
else if (Config.UNIQUE_ID && (parts = selector.match(Optimize.ID)) && (token = parts[1])) {
if ((element = _byId(token, doc))) {
if ('#' + token == selector) {
callback && callback(element);
elements = [element];
} else if (/[>+~]/.test(selector)) {
from = element.parentNode;
} else {
from = element;
}
} else elements = [ ];
}
if (elements) {
Config.CACHING && Dom.saveResults(original, from, doc, elements);
return elements;
}
if (!XML_DOCUMENT && GEBTN && lastSlice && (parts = lastSlice.match(Optimize.TAG)) && (token = parts[1])) {
if ((elements = from.getElementsByTagName(token)).length === 0) { return [ ]; }
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace(token, '*');
}
else if (!XML_DOCUMENT && GEBCN && lastSlice && (parts = lastSlice.match(Optimize.CLASS)) && (token = parts[1])) {
if ((elements = from.getElementsByClassName(unescapeIdentifier(token))).length === 0) { return [ ]; }
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace('.' + token,
reOptimizeSelector.test(selector.charAt(selector.indexOf(token) - 1)) ? '' : '*');
}
}
if (!elements) {
if (IE_LT_9) {
elements = /^(?:applet|object)$/i.test(from.nodeName) ? from.children : byTagRaw('*', from);
} else {
elements = from.getElementsByTagName('*');
}
}
if (!selectResolvers[selector] || selectContexts[selector] !== from) {
selectResolvers[selector] = compile(isSingleSelect ? [selector] : parts, REJECT_NODE, true);
selectContexts[selector] = from;
}
elements = selectResolvers[selector](elements, Snapshot, doc, root, from, callback);
Config.CACHING && Dom.saveResults(original, from, doc, elements);
return elements;
},
FN = function(x) { return x; },
matchContexts = { },
matchResolvers = { },
selectContexts = { },
selectResolvers = { },
Snapshot = {
byId: _byId,
match: match,
select: select,
isLink: isLink,
isEmpty: isEmpty,
contains: contains,
nthOfType: nthOfType,
nthElement: nthElement,
getAttribute: getAttribute,
hasAttribute: hasAttribute
},
Dom = {
ACCEPT_NODE: ACCEPT_NODE,
byId: byId,
match: match,
first: first,
select: select,
compile: compile,
contains: contains,
configure: configure,
getAttribute: getAttribute,
hasAttribute: hasAttribute,
setCache: FN,
shortcuts: FN,
loadResults: FN,
saveResults: FN,
emit: emit,
Config: Config,
Snapshot: Snapshot,
Operators: Operators,
Selectors: Selectors,
Tokens: Tokens,
Version: version,
registerOperator:
function(symbol, resolver) {
Operators[symbol] || (Operators[symbol] = resolver);
},
registerSelector:
function(name, rexp, func) {
Selectors[name] || (Selectors[name] = {
Expression: rexp,
Callback: func
});
}
};
initialize(doc);
return Dom;
});
``` | /content/code_sandbox/node_modules/nwmatcher/src/nwmatcher-noqsa.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 8,849 |
```javascript
/*
* All rights reserved.
*
* nwmatcher.js - A fast CSS selector engine and matcher
*
* Author: Diego Perini <diego.perini at gmail com>
* Version: 1.4.4
* Created: 20070722
* Release: 20180305
*
* path_to_url
* Download:
* path_to_url
*/
(function(global, factory) {
if (typeof module == 'object' && typeof exports == 'object') {
module.exports = factory;
} else if (typeof define === 'function' && define["amd"]) {
define(factory);
} else {
global.NW || (global.NW = { });
global.NW.Dom = factory(global);
}
})(this, function(global) {
var version = 'nwmatcher-1.4.4',
// processing context & root element
doc = global.document,
root = doc.documentElement,
// save utility methods references
slice = [ ].slice,
// persist previous parsed data
isSingleMatch,
isSingleSelect,
lastSlice,
lastContext,
lastPosition,
lastMatcher,
lastSelector,
lastPartsMatch,
lastPartsSelect,
// accepted prefix identifiers
// (id, class & pseudo-class)
prefixes = '(?:[#.:]|::)?',
// accepted attribute operators
operators = '([~*^$|!]?={1})',
// accepted whitespace characters
whitespace = '[\\x20\\t\\n\\r\\f]',
// 4 combinators F E, F>E, F+E, F~E
combinators = '\\x20|[>+~](?=[^>+~])',
// an+b format params for pseudo-classes
pseudoparms = '(?:[-+]?\\d*n)?[-+]?\\d*',
// skip [ ], ( ), { } brackets groups
skip_groups = '\\[.*\\]|\\(.*\\)|\\{.*\\}',
// any escaped char
any_esc_chr = '\\\\.',
// alpha chars & low dash
alphalodash = '[_a-zA-Z]',
// non-ascii chars (utf-8)
non_asc_chr = '[^\\x00-\\x9f]',
// escape sequences in strings
escaped_chr = '\\\\[^\\n\\r\\f0-9a-fA-F]',
// Unicode chars including trailing whitespace
unicode_chr = '\\\\[0-9a-fA-F]{1,6}(?:\\r\\n|' + whitespace + ')?',
// CSS quoted string values
quotedvalue = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"' + "|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'",
// regular expression used to skip single/nested brackets groups (round, square, curly)
// used to split comma groups excluding commas inside quotes '' "" or brackets () [] {}
reSplitGroup = /([^,\\()[\]]+|\[[^[\]]*\]|\[.*\]|\([^()]+\)|\(.*\)|\{[^{}]+\}|\{.*\}|\\.)+/g,
// regular expression to trim extra leading/trailing whitespace in selector strings
// whitespace is any combination of these 5 character [\x20\t\n\r\f]
// path_to_url#selector-syntax
reTrimSpaces = RegExp('[\\n\\r\\f]|^' + whitespace + '+|' + whitespace + '+$', 'g'),
// regular expression used in convertEscapes and unescapeIdentifier
reEscapedChars = /\\([0-9a-fA-F]{1,6}[\x20\t\n\r\f]?|.)|([\x22\x27])/g,
// for in excess whitespace removal
reWhiteSpace = /[\x20\t\n\r\f]+/g,
standardValidator, extendedValidator, reValidator,
attrcheck, attributes, attrmatcher, pseudoclass,
reOptimizeSelector, reSimpleNot, reSplitToken,
Optimize, reClass, reSimpleSelector,
// path_to_url#characters
// unicode/ISO 10646 characters \xA0 and higher
// NOTE: Safari 2.0.x crashes with escaped (\\)
// Unicode ranges in regular expressions so we
// use a negated character range class instead
// now assigned at runtime from config options
identifier,
// placeholder for extensions
extensions = '.+',
// precompiled Regular Expressions
Patterns = {
// structural pseudo-classes and child selectors
spseudos: /^\:(root|empty|(?:first|last|only)(?:-child|-of-type)|nth(?:-last)?(?:-child|-of-type)\(\s?(even|odd|(?:[-+]{0,1}\d*n\s?)?[-+]{0,1}\s?\d*)\s?\))?(.*)/i,
// uistates + dynamic + negation pseudo-classes
dpseudos: /^\:(link|visited|target|active|focus|hover|checked|disabled|enabled|selected|lang\(([-\w]{2,})\)|(?:matches|not)\(\s?(:nth(?:-last)?(?:-child|-of-type)\(\s?(?:even|odd|(?:[-+]{0,1}\d*n\s?)?[-+]{0,1}\s?\d*)\s?\)|[^()]*)\s?\))?(.*)/i,
// pseudo-elements selectors
epseudos: /^((?:[:]{1,2}(?:after|before|first-letter|first-line))|(?:[:]{2,2}(?:selection|backdrop|placeholder)))?(.*)/i,
// E > F
children: RegExp('^' + whitespace + '?\\>' + whitespace + '?(.*)'),
// E + F
adjacent: RegExp('^' + whitespace + '?\\+' + whitespace + '?(.*)'),
// E ~ F
relative: RegExp('^' + whitespace + '?\\~' + whitespace + '?(.*)'),
// E F
ancestor: RegExp('^' + whitespace + '+(.*)'),
// all
universal: RegExp('^\\*(.*)')
},
Tokens = {
prefixes: prefixes,
identifier: identifier,
attributes: attributes
},
/*----------------------------- FEATURE TESTING ----------------------------*/
// detect native methods
isNative = (function() {
var re = / \w+\(/,
isnative = String(({ }).toString).replace(re, ' (');
return function(method) {
return method && typeof method != 'string' &&
isnative == String(method).replace(re, ' (');
};
})(),
// NATIVE_XXXXX true if method exist and is callable
// detect if DOM methods are native in browsers
NATIVE_FOCUS = isNative(doc.hasFocus),
NATIVE_QSAPI = isNative(doc.querySelector),
NATIVE_GEBID = isNative(doc.getElementById),
NATIVE_GEBTN = isNative(root.getElementsByTagName),
NATIVE_GEBCN = isNative(root.getElementsByClassName),
// detect native getAttribute/hasAttribute methods,
// frameworks extend these to elements, but it seems
// this does not work for XML namespaced attributes,
// used to check both getAttribute/hasAttribute in IE
NATIVE_GET_ATTRIBUTE = isNative(root.getAttribute),
NATIVE_HAS_ATTRIBUTE = isNative(root.hasAttribute),
// check if slice() can convert nodelist to array
// see path_to_url
NATIVE_SLICE_PROTO =
(function() {
var isBuggy = false;
try {
isBuggy = !!slice.call(doc.childNodes, 0)[0];
} catch(e) { }
return isBuggy;
})(),
// supports the new traversal API
NATIVE_TRAVERSAL_API =
'nextElementSibling' in root && 'previousElementSibling' in root,
// BUGGY_XXXXX true if method is feature tested and has known bugs
// detect buggy gEBID
BUGGY_GEBID = NATIVE_GEBID ?
(function() {
var isBuggy = true, x = 'x' + String(+new Date),
a = doc.createElementNS ? 'a' : '<a name="' + x + '">';
(a = doc.createElement(a)).name = x;
root.insertBefore(a, root.firstChild);
isBuggy = !!doc.getElementById(x);
root.removeChild(a);
return isBuggy;
})() :
true,
// detect IE gEBTN comment nodes bug
BUGGY_GEBTN = NATIVE_GEBTN ?
(function() {
var div = doc.createElement('div');
div.appendChild(doc.createComment(''));
return !!div.getElementsByTagName('*')[0];
})() :
true,
// detect Opera gEBCN second class and/or UTF8 bugs as well as Safari 3.2
// caching class name results and not detecting when changed,
// tests are based on the jQuery selector test suite
BUGGY_GEBCN = NATIVE_GEBCN ?
(function() {
var isBuggy, div = doc.createElement('div'), test = '\u53f0\u5317';
// Opera tests
div.appendChild(doc.createElement('span')).
setAttribute('class', test + 'abc ' + test);
div.appendChild(doc.createElement('span')).
setAttribute('class', 'x');
isBuggy = !div.getElementsByClassName(test)[0];
// Safari test
div.lastChild.className = test;
return isBuggy || div.getElementsByClassName(test).length != 2;
})() :
true,
// detect IE bug with dynamic attributes
BUGGY_GET_ATTRIBUTE = NATIVE_GET_ATTRIBUTE ?
(function() {
var input = doc.createElement('input');
input.setAttribute('value', 5);
return input.defaultValue != 5;
})() :
true,
// detect IE bug with non-standard boolean attributes
BUGGY_HAS_ATTRIBUTE = NATIVE_HAS_ATTRIBUTE ?
(function() {
var option = doc.createElement('option');
option.setAttribute('selected', 'selected');
return !option.hasAttribute('selected');
})() :
true,
// detect Safari bug with selected option elements
BUGGY_SELECTED =
(function() {
var select = doc.createElement('select');
select.appendChild(doc.createElement('option'));
return !select.firstChild.selected;
})(),
// initialized with the loading context
// and reset for each different context
BUGGY_QUIRKS_GEBCN,
BUGGY_QUIRKS_QSAPI,
QUIRKS_MODE,
XML_DOCUMENT,
// detect Opera browser
OPERA = typeof global.opera != 'undefined' &&
(/opera/i).test(({ }).toString.call(global.opera)),
// skip simple selector optimizations for Opera >= 11
OPERA_QSAPI = OPERA && parseFloat(global.opera.version()) >= 11,
// check Selector API implementations
RE_BUGGY_QSAPI = NATIVE_QSAPI ?
(function() {
var pattern = [ ], context, element,
expect = function(selector, element, n) {
var result = false;
context.appendChild(element);
try { result = context.querySelectorAll(selector).length == n; } catch(e) { }
while (context.firstChild) { context.removeChild(context.firstChild); }
return result;
};
// certain bugs can only be detected in standard documents
// to avoid writing a live loading document create a fake one
if (doc.implementation && doc.implementation.createDocument) {
// use a shadow document body as context
context = doc.implementation.createDocument('', '', null).
appendChild(doc.createElement('html')).
appendChild(doc.createElement('head')).parentNode.
appendChild(doc.createElement('body'));
} else {
// use an unattached div node as context
context = doc.createElement('div');
}
// fix for Safari 8.x and other engines that
// fail querying filtered sibling combinators
element = doc.createElement('div');
element.innerHTML = '<p id="a"></p><br>';
expect('p#a+*', element, 0) &&
pattern.push('\\w+#\\w+.*[+~]');
// ^= $= *= operators bugs with empty values (Opera 10 / IE8)
element = doc.createElement('p');
element.setAttribute('class', '');
expect('[class^=""]', element, 1) &&
pattern.push('[*^$]=[\\x20\\t\\n\\r\\f]*(?:""|' + "'')");
// :checked bug with option elements (Firefox 3.6.x)
// it wrongly includes 'selected' options elements
// HTML5 rules says selected options also match
element = doc.createElement('option');
element.setAttribute('selected', 'selected');
expect(':checked', element, 0) &&
pattern.push(':checked');
// :enabled :disabled bugs with hidden fields (Firefox 3.5)
// path_to_url#selector-enabled
// path_to_url#enableddisabled
// not supported by IE8 Query Selector
element = doc.createElement('input');
element.setAttribute('type', 'hidden');
expect(':enabled', element, 0) &&
pattern.push(':enabled', ':disabled');
// :link bugs with hyperlinks matching (Firefox/Safari)
element = doc.createElement('link');
element.setAttribute('href', 'x');
expect(':link', element, 1) ||
pattern.push(':link');
// avoid attribute selectors for IE QSA
if (BUGGY_HAS_ATTRIBUTE) {
// IE fails in reading:
// - original values for input/textarea
// - original boolean values for controls
pattern.push('\\[[\\x20\\t\\n\\r\\f]*(?:checked|disabled|ismap|multiple|readonly|selected|value)');
}
return pattern.length ?
RegExp(pattern.join('|')) :
{ 'test': function() { return false; } };
})() :
true,
/*----------------------------- LOOKUP OBJECTS -----------------------------*/
IE_LT_9 = typeof doc.addEventListener != 'function',
LINK_NODES = { 'a': 1, 'A': 1, 'area': 1, 'AREA': 1, 'link': 1, 'LINK': 1 },
// boolean attributes should return attribute name instead of true/false
ATTR_BOOLEAN = {
'checked': 1, 'disabled': 1, 'ismap': 1,
'multiple': 1, 'readonly': 1, 'selected': 1
},
// dynamic attributes that needs to be checked against original HTML value
ATTR_DEFAULT = {
'value': 'defaultValue',
'checked': 'defaultChecked',
'selected': 'defaultSelected'
},
// attributes referencing URI data values need special treatment in IE
ATTR_URIDATA = {
'action': 2, 'cite': 2, 'codebase': 2, 'data': 2, 'href': 2,
'longdesc': 2, 'lowsrc': 2, 'src': 2, 'usemap': 2
},
// HTML 5 draft specifications
// path_to_url#selectors
HTML_TABLE = {
// NOTE: class name attribute selectors must always be treated using a
// case-sensitive match, this has changed from previous specifications
'accept': 1, 'accept-charset': 1, 'align': 1, 'alink': 1, 'axis': 1,
'bgcolor': 1, 'charset': 1, 'checked': 1, 'clear': 1, 'codetype': 1, 'color': 1,
'compact': 1, 'declare': 1, 'defer': 1, 'dir': 1, 'direction': 1, 'disabled': 1,
'enctype': 1, 'face': 1, 'frame': 1, 'hreflang': 1, 'http-equiv': 1, 'lang': 1,
'language': 1, 'link': 1, 'media': 1, 'method': 1, 'multiple': 1, 'nohref': 1,
'noresize': 1, 'noshade': 1, 'nowrap': 1, 'readonly': 1, 'rel': 1, 'rev': 1,
'rules': 1, 'scope': 1, 'scrolling': 1, 'selected': 1, 'shape': 1, 'target': 1,
'text': 1, 'type': 1, 'valign': 1, 'valuetype': 1, 'vlink': 1
},
/*-------------------------- REGULAR EXPRESSIONS ---------------------------*/
// placeholder to add functionalities
Selectors = {
// as a simple example this will check
// for chars not in standard ascii table
//
// 'mySpecialSelector': {
// 'Expression': /\u0080-\uffff/,
// 'Callback': mySelectorCallback
// }
//
// 'mySelectorCallback' will be invoked
// only after passing all other standard
// checks and only if none of them worked
},
// attribute operators
Operators = {
'=': "n=='%m'",
'^=': "n.indexOf('%m')==0",
'*=': "n.indexOf('%m')>-1",
'|=': "(n+'-').indexOf('%m-')==0",
'~=': "(' '+n+' ').indexOf(' %m ')>-1",
'$=': "n.substr(n.length-'%m'.length)=='%m'"
},
/*------------------------------ UTIL METHODS ------------------------------*/
// concat elements to data
concatList =
function(data, elements) {
var i = -1, element;
if (!data.length && Array.slice)
return Array.slice(elements);
while ((element = elements[++i]))
data[data.length] = element;
return data;
},
// concat elements to data and callback
concatCall =
function(data, elements, callback) {
var i = -1, element;
while ((element = elements[++i])) {
if (false === callback(data[data.length] = element)) { break; }
}
return data;
},
// change context specific variables
switchContext =
function(from, force) {
var div, oldDoc = doc;
// save passed context
lastContext = from;
// set new context document
doc = from.ownerDocument || from;
if (force || oldDoc !== doc) {
// set document root
root = doc.documentElement;
// set host environment flags
XML_DOCUMENT = doc.createElement('DiV').nodeName == 'DiV';
// In quirks mode css class names are case insensitive.
// In standards mode they are case sensitive. See docs:
// path_to_url
// path_to_url#selectors
QUIRKS_MODE = !XML_DOCUMENT &&
typeof doc.compatMode == 'string' ?
doc.compatMode.indexOf('CSS') < 0 :
(function() {
var style = doc.createElement('div').style;
return style && (style.width = 1) && style.width == '1px';
})();
div = doc.createElement('div');
div.appendChild(doc.createElement('p')).setAttribute('class', 'xXx');
div.appendChild(doc.createElement('p')).setAttribute('class', 'xxx');
// GEBCN buggy in quirks mode, match count is:
// Firefox 3.0+ [xxx = 1, xXx = 1]
// Opera 10.63+ [xxx = 0, xXx = 2]
BUGGY_QUIRKS_GEBCN =
!XML_DOCUMENT && NATIVE_GEBCN && QUIRKS_MODE &&
(div.getElementsByClassName('xxx').length != 2 ||
div.getElementsByClassName('xXx').length != 2);
// QSAPI buggy in quirks mode, match count is:
// At least Chrome 4+, Firefox 3.5+, Opera 10.x+, Safari 4+ [xxx = 1, xXx = 2]
// Safari 3.2 QSA doesn't work with mixedcase in quirksmode [xxx = 1, xXx = 0]
// path_to_url
// must test the attribute selector '[class~=xxx]'
// before '.xXx' or the bug may not present itself
BUGGY_QUIRKS_QSAPI =
!XML_DOCUMENT && NATIVE_QSAPI && QUIRKS_MODE &&
(div.querySelectorAll('[class~=xxx]').length != 2 ||
div.querySelectorAll('.xXx').length != 2);
Config.CACHING && Dom.setCache(true, doc);
}
},
// convert single codepoint to UTF-16 encoding
codePointToUTF16 =
function(codePoint) {
// out of range, use replacement character
if (codePoint < 1 || codePoint > 0x10ffff ||
(codePoint > 0xd7ff && codePoint < 0xe000)) {
return '\\ufffd';
}
// javascript strings are UTF-16 encoded
if (codePoint < 0x10000) {
var lowHex = '000' + codePoint.toString(16);
return '\\u' + lowHex.substr(lowHex.length - 4);
}
// supplementary high + low surrogates
return '\\u' + (((codePoint - 0x10000) >> 0x0a) + 0xd800).toString(16) +
'\\u' + (((codePoint - 0x10000) % 0x400) + 0xdc00).toString(16);
},
// convert single codepoint to string
stringFromCodePoint =
function(codePoint) {
// out of range, use replacement character
if (codePoint < 1 || codePoint > 0x10ffff ||
(codePoint > 0xd7ff && codePoint < 0xe000)) {
return '\ufffd';
}
if (codePoint < 0x10000) {
return String.fromCharCode(codePoint);
}
return String.fromCodePoint ?
String.fromCodePoint(codePoint) :
String.fromCharCode(
((codePoint - 0x10000) >> 0x0a) + 0xd800,
((codePoint - 0x10000) % 0x400) + 0xdc00);
},
// convert escape sequence in a CSS string or identifier
// to javascript string with javascript escape sequences
convertEscapes =
function(str) {
return str.replace(reEscapedChars,
function(substring, p1, p2) {
// unescaped " or '
return p2 ? '\\' + p2 :
// javascript strings are UTF-16 encoded
(/^[0-9a-fA-F]/).test(p1) ? codePointToUTF16(parseInt(p1, 16)) :
// \' \"
(/^[\\\x22\x27]/).test(p1) ? substring :
// \g \h \. \# etc
p1;
}
);
},
// convert escape sequence in a CSS string or identifier
// to javascript string with characters representations
unescapeIdentifier =
function(str) {
return str.replace(reEscapedChars,
function(substring, p1, p2) {
// unescaped " or '
return p2 ? p2 :
// javascript strings are UTF-16 encoded
(/^[0-9a-fA-F]/).test(p1) ? stringFromCodePoint(parseInt(p1, 16)) :
// \' \"
(/^[\\\x22\x27]/).test(p1) ? substring :
// \g \h \. \# etc
p1;
}
);
},
/*------------------------------ DOM METHODS -------------------------------*/
// element by id (raw)
// @return reference or null
byIdRaw =
function(id, elements) {
var i = -1, element;
while ((element = elements[++i])) {
if (element.getAttribute('id') == id) {
break;
}
}
return element || null;
},
// element by id
// @return reference or null
_byId = !BUGGY_GEBID ?
function(id, from) {
id = (/\\/).test(id) ? unescapeIdentifier(id) : id;
return from.getElementById && from.getElementById(id) ||
byIdRaw(id, from.getElementsByTagName('*'));
} :
function(id, from) {
var element = null;
id = (/\\/).test(id) ? unescapeIdentifier(id) : id;
if (XML_DOCUMENT || from.nodeType != 9) {
return byIdRaw(id, from.getElementsByTagName('*'));
}
if ((element = from.getElementById(id)) &&
element.name == id && from.getElementsByName) {
return byIdRaw(id, from.getElementsByName(id));
}
return element;
},
// publicly exposed byId
// @return reference or null
byId =
function(id, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byId(id, from);
},
// elements by tag (raw)
// @return array
byTagRaw =
function(tag, from) {
var any = tag == '*', element = from, elements = [ ], next = element.firstChild;
any || (tag = tag.toUpperCase());
while ((element = next)) {
if (element.tagName > '@' && (any || element.tagName.toUpperCase() == tag)) {
elements[elements.length] = element;
}
if ((next = element.firstChild || element.nextSibling)) continue;
while (!next && (element = element.parentNode) && element !== from) {
next = element.nextSibling;
}
}
return elements;
},
// elements by tag
// @return array
_byTag = !BUGGY_GEBTN && NATIVE_SLICE_PROTO ?
function(tag, from) {
return XML_DOCUMENT || from.nodeType == 11 ? byTagRaw(tag, from) :
slice.call(from.getElementsByTagName(tag), 0);
} :
function(tag, from) {
var i = -1, j = i, data = [ ], element,
elements = XML_DOCUMENT || from.nodeType == 11 ?
byTagRaw(tag, from) : from.getElementsByTagName(tag);
if (tag == '*') {
while ((element = elements[++i])) {
if (element.nodeName > '@') {
data[++j] = element;
}
}
} else {
while ((element = elements[++i])) {
data[i] = element;
}
}
return data;
},
// publicly exposed byTag
// @return array
byTag =
function(tag, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byTag(tag, from);
},
// publicly exposed byName
// @return array
byName =
function(name, from) {
return select('[name="' + name.replace(/\\([^\\]{1})/g, '$1') + '"]', from);
},
// elements by class (raw)
// @return array
byClassRaw =
function(name, from) {
var i = -1, j = i, data = [ ], element, elements = _byTag('*', from), n;
name = ' ' + (QUIRKS_MODE ? name.toLowerCase() : name) + ' ';
while ((element = elements[++i])) {
n = XML_DOCUMENT ? element.getAttribute('class') : element.className;
if (n && n.length && (' ' + (QUIRKS_MODE ? n.toLowerCase() : n).
replace(reWhiteSpace, ' ') + ' ').indexOf(name) > -1) {
data[++j] = element;
}
}
return data;
},
// elements by class
// @return array
_byClass =
function(name, from) {
name = QUIRKS_MODE ? name.toLowerCase() : name;
name = (/\\/).test(name) ? unescapeIdentifier(name) : name;
return (BUGGY_GEBCN || BUGGY_QUIRKS_GEBCN || XML_DOCUMENT || !from.getElementsByClassName) ?
byClassRaw(name, from) : slice.call(from.getElementsByClassName(name));
},
// publicly exposed byClass
// @return array
byClass =
function(name, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byClass(name, from);
},
// check element is descendant of container
// @return boolean
contains = 'compareDocumentPosition' in root ?
function(container, element) {
return (container.compareDocumentPosition(element) & 16) == 16;
} : 'contains' in root ?
function(container, element) {
return container !== element && container.contains(element);
} :
function(container, element) {
while ((element = element.parentNode)) {
if (element === container) return true;
}
return false;
},
// attribute value
// @return string
getAttribute = !BUGGY_GET_ATTRIBUTE && !IE_LT_9 ?
function(node, attribute) {
return node.getAttribute(attribute);
} :
function(node, attribute) {
attribute = attribute.toLowerCase();
if (typeof node[attribute] == 'object') {
return node.attributes[attribute] &&
node.attributes[attribute].value;
}
return (
// 'type' can only be read by using native getAttribute
attribute == 'type' ? node.getAttribute(attribute) :
// specific URI data attributes (parameter 2 to fix IE bug)
ATTR_URIDATA[attribute] ? node.getAttribute(attribute, 2) :
// boolean attributes should return name instead of true/false
ATTR_BOOLEAN[attribute] ? node.getAttribute(attribute) ? attribute : 'false' :
(node = node.getAttributeNode(attribute)) && node.value);
},
// attribute presence
// @return boolean
hasAttribute = !BUGGY_HAS_ATTRIBUTE && !IE_LT_9 ?
function(node, attribute) {
return XML_DOCUMENT ?
!!node.getAttribute(attribute) :
node.hasAttribute(attribute);
} :
function(node, attribute) {
// read the node attribute object
var obj = node.getAttributeNode(attribute = attribute.toLowerCase());
return ATTR_DEFAULT[attribute] && attribute != 'value' ?
node[ATTR_DEFAULT[attribute]] : obj && obj.specified;
},
// check node emptyness
// @return boolean
isEmpty =
function(node) {
node = node.firstChild;
while (node) {
if (node.nodeType == 3 || node.nodeName > '@') return false;
node = node.nextSibling;
}
return true;
},
// check if element matches the :link pseudo
// @return boolean
isLink =
function(element) {
return hasAttribute(element,'href') && LINK_NODES[element.nodeName];
},
// child position by nodeType
// @return number
nthElement =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling';
while ((element = element[succ])) {
if (element.nodeName > '@') ++count;
}
return count;
},
// child position by nodeName
// @return number
nthOfType =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling', type = element.nodeName;
while ((element = element[succ])) {
if (element.nodeName == type) ++count;
}
return count;
},
/*------------------------------- DEBUGGING --------------------------------*/
// get/set (string/object) working modes
configure =
function(option) {
if (typeof option == 'string') { return !!Config[option]; }
if (typeof option != 'object') { return Config; }
for (var i in option) {
Config[i] = !!option[i];
if (i == 'SIMPLENOT') {
matchContexts = { };
matchResolvers = { };
selectContexts = { };
selectResolvers = { };
if (!Config[i]) { Config['USE_QSAPI'] = false; }
} else if (i == 'USE_QSAPI') {
Config[i] = !!option[i] && NATIVE_QSAPI;
}
}
setIdentifierSyntax();
reValidator = RegExp(Config.SIMPLENOT ?
standardValidator : extendedValidator);
return true;
},
// control user notifications
emit =
function(message) {
if (Config.VERBOSITY) { throw Error(message); }
if (Config.LOGERRORS && console && console.log) {
console.log(message);
}
},
Config = {
// true to enable caching of result sets, false to disable
CACHING: false,
// true to allow CSS escaped identifiers, false to disallow
ESCAPECHR: true,
// true to allow identifiers containing non-ASCII (utf-8) chars
NON_ASCII: true,
// switch syntax RE, true to use Level 3, false to use Level 2
SELECTOR3: true,
// true to allow identifiers containing Unicode (utf-16) chars
UNICODE16: true,
// by default do not add missing left/right context
// to mangled selector strings like "+div" or "ul>"
// callable Dom.shortcuts method has to be available
SHORTCUTS: false,
// true to disable complex selectors nested in
// ':not()' pseudo-classes as for specifications
SIMPLENOT: true,
// true to match lowercase tag names of SVG elements in HTML
SVG_LCASE: false,
// strict QSA match all non-unique IDs (false)
// speed & libs compat match unique ID (true)
UNIQUE_ID: true,
// true to follow HTML5 specs handling of ":checked"
// pseudo-class and similar UI states (indeterminate)
USE_HTML5: true,
// true to use browsers native Query Selector API if available
USE_QSAPI: NATIVE_QSAPI,
// true to throw exceptions, false to skip throwing exceptions
VERBOSITY: true,
// true to print console errors or warnings, false to mute them
LOGERRORS: true
},
/*---------------------------- COMPILER METHODS ----------------------------*/
// init REs and context
initialize =
function(doc) {
setIdentifierSyntax();
switchContext(doc, true);
},
// set/reset default identifier syntax
// based on user configuration options
// rebuild the validator and other REs
setIdentifierSyntax =
function() {
var syntax = '', start = Config['SELECTOR3'] ? '-{2}|' : '';
Config['NON_ASCII'] && (syntax += '|' + non_asc_chr);
Config['UNICODE16'] && (syntax += '|' + unicode_chr);
Config['ESCAPECHR'] && (syntax += '|' + escaped_chr);
syntax += (Config['UNICODE16'] || Config['ESCAPECHR']) ? '' : '|' + any_esc_chr;
identifier = '-?(?:' + start + alphalodash + syntax + ')(?:-|[0-9]|' + alphalodash + syntax + ')*';
// build attribute string
attrcheck = '(' + quotedvalue + '|' + identifier + ')';
attributes = whitespace + '*(' + identifier + '(?::' + identifier + ')?)' +
whitespace + '*(?:' + operators + whitespace + '*' + attrcheck + ')?' + whitespace + '*' + '(i)?' + whitespace + '*';
attrmatcher = attributes.replace(attrcheck, '([\\x22\\x27]*)((?:\\\\?.)*?)\\3');
// build pseudoclass string
pseudoclass = '((?:' +
// an+b parameters or quoted string
pseudoparms + '|' + quotedvalue + '|' +
// id, class, pseudo-class selector
prefixes + identifier + '|' +
// nested HTML attribute selector
'\\[' + attributes + '\\]|' +
// nested pseudo-class selector
'\\(.+\\)|' + whitespace + '*|' +
// nested pseudos/separators
',)+)';
// CSS3: syntax scanner and
// one pass validation only
// using regular expression
standardValidator =
// discard start
'(?=[\\x20\\t\\n\\r\\f]*[^>+~(){}<>])' +
// open match group
'(' +
//universal selector
'\\*' +
// id/class/tag/pseudo-class identifier
'|(?:' + prefixes + identifier + ')' +
// combinator selector
'|' + combinators +
// HTML attribute selector
'|\\[' + attributes + '\\]' +
// pseudo-classes parameters
'|\\(' + pseudoclass + '\\)' +
// dom properties selector (extension)
'|\\{' + extensions + '\\}' +
// selector group separator (comma)
'|(?:,|' + whitespace + '*)' +
// close match group
')+';
// only allow simple selectors nested in ':not()' pseudo-classes
reSimpleNot = RegExp('^(' +
'(?!:not)' +
'(' + prefixes + identifier +
'|\\([^()]*\\))+' +
'|\\[' + attributes + '\\]' +
')$');
// split last, right most, selector group token
reSplitToken = RegExp('(' +
prefixes + identifier + '|' +
'\\[' + attributes + '\\]|' +
'\\(' + pseudoclass + '\\)|' +
'\\\\.|[^\\x20\\t\\n\\r\\f>+~])+', 'g');
reOptimizeSelector = RegExp(identifier + '|^$');
reSimpleSelector = RegExp(
BUGGY_GEBTN && BUGGY_GEBCN || OPERA ?
'^#?' + identifier + '$' : BUGGY_GEBTN ?
'^[.#]?' + identifier + '$' : BUGGY_GEBCN ?
'^(?:\\*|#' + identifier + ')$' :
'^(?:\\*|[.#]?' + identifier + ')$');
// matches class selectors
reClass = RegExp('(?:\\[[\\x20\\t\\n\\r\\f]*class\\b|\\.' + identifier + ')');
Optimize = {
ID: RegExp('^\\*?#(' + identifier + ')|' + skip_groups),
TAG: RegExp('^(' + identifier + ')|' + skip_groups),
CLASS: RegExp('^\\.(' + identifier + '$)|' + skip_groups)
};
Patterns.id = RegExp('^#(' + identifier + ')(.*)');
Patterns.tagName = RegExp('^(' + identifier + ')(.*)');
Patterns.className = RegExp('^\\.(' + identifier + ')(.*)');
Patterns.attribute = RegExp('^\\[' + attrmatcher + '\\](.*)');
Tokens.identifier = identifier;
Tokens.attributes = attributes;
// validator for complex selectors in ':not()' pseudo-classes
extendedValidator = standardValidator.replace(pseudoclass, '.*');
// validator for standard selectors as default
reValidator = RegExp(standardValidator);
},
// code string reused to build compiled functions
ACCEPT_NODE = 'r[r.length]=c[k];if(f&&false===f(c[k]))break main;else continue main;',
// compile a comma separated group of selector
// @mode boolean true for select, false for match
// return a compiled function
compile =
function(selector, source, mode) {
var parts = typeof selector == 'string' ? selector.match(reSplitGroup) : selector;
// ensures that source is a string
typeof source == 'string' || (source = '');
if (parts.length == 1) {
source += compileSelector(parts[0], mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
} else {
// for each selector in the group
var i = -1, seen = { }, token;
while ((token = parts[++i])) {
token = token.replace(reTrimSpaces, '');
// avoid repeating the same token
// in comma separated group (p, p)
if (!seen[token] && (seen[token] = true)) {
source += compileSelector(token, mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
}
}
}
if (mode) {
// for select method
return Function('c,s,d,h,g,f',
'var N,n,x=0,k=-1,e,r=[];main:while((e=c[++k])){' + source + '}return r;');
} else {
// for match method
return Function('e,s,d,h,g,f',
'var N,n,x=0,k=e;' + source + 'return false;');
}
},
// compile a CSS3 string selector into ad-hoc javascript matching function
// @return string (to be compiled)
compileSelector =
function(selector, source, mode) {
var a, b, n, k = 0, expr, match, result, status, test, type;
while (selector) {
k++;
// *** Universal selector
// * match all (empty block, do not remove)
if ((match = selector.match(Patterns.universal))) {
// do nothing, handled in the compiler where
// BUGGY_GEBTN return comment nodes (ex: IE)
expr = '';
}
// *** ID selector
// #Foo Id case sensitive
else if ((match = selector.match(Patterns.id))) {
// document can contain conflicting elements (id/name)
// prototype selector unit need this method to recover bad HTML forms
match[1] = (/\\/).test(match[1]) ? convertEscapes(match[1]) : match[1];
source = 'if(' + (XML_DOCUMENT ?
's.getAttribute(e,"id")' :
'(e.submit?s.getAttribute(e,"id"):e.id)') +
'=="' + match[1] + '"' +
'){' + source + '}';
}
// *** Type selector
// Foo Tag (case insensitive)
else if ((match = selector.match(Patterns.tagName))) {
// both tagName and nodeName properties may be upper/lower case
// depending on their creation NAMESPACE in createElementNS()
test = Config.SVG_LCASE ? '||e.nodeName=="' + match[1].toLowerCase() + '"' : '';
source = 'if(e.nodeName' + (XML_DOCUMENT ?
'=="' + match[1] + '"' : '.toUpperCase()' +
'=="' + match[1].toUpperCase() + '"' + test) +
'){' + source + '}';
}
// *** Class selector
// .Foo Class (case sensitive)
else if ((match = selector.match(Patterns.className))) {
// W3C CSS3 specs: element whose "class" attribute has been assigned a
// list of whitespace-separated values, see section 6.4 Class selectors
// and notes at the bottom; explicitly non-normative in this specification.
match[1] = (/\\/).test(match[1]) ? convertEscapes(match[1]) : match[1];
match[1] = QUIRKS_MODE ? match[1].toLowerCase() : match[1];
source = 'if((n=' + (XML_DOCUMENT ?
's.getAttribute(e,"class")' : 'e.className') +
')&&n.length&&(" "+' + (QUIRKS_MODE ? 'n.toLowerCase()' : 'n') +
'.replace(/' + whitespace + '+/g," ")+" ").indexOf(" ' + match[1] + ' ")>-1' +
'){' + source + '}';
}
// *** Attribute selector
// [attr] [attr=value] [attr="value"] [attr='value'] and !=, *=, ~=, |=, ^=, $=
// case sensitivity is treated differently depending on the document type (see map)
else if ((match = selector.match(Patterns.attribute))) {
// xml namespaced attribute ?
expr = match[1].split(':');
expr = expr.length == 2 ? expr[1] : expr[0] + '';
if (match[2] && !Operators[match[2]]) {
emit('Unsupported operator in attribute selectors "' + selector + '"');
return '';
}
test = 'false';
// replace Operators parameter if needed
if (match[2] && match[4] && (test = Operators[match[2]])) {
match[4] = (/\\/).test(match[4]) ? convertEscapes(match[4]) : match[4];
// case treatment depends on document type
type = match[5] == 'i' || HTML_TABLE[expr.toLowerCase()];
test = test.replace(/\%m/g, type ? match[4].toLowerCase() : match[4]);
} else if (match[2] == '!=' || match[2] == '=') {
test = 'n' + match[2] + '=""';
}
source = 'if(n=s.hasAttribute(e,"' + match[1] + '")){' +
(match[2] ? 'n=s.getAttribute(e,"' + match[1] + '")' : '') +
(type && match[2] ? '.toLowerCase();' : ';') +
'if(' + (match[2] ? test : 'n') + '){' + source + '}}';
}
// *** Adjacent sibling combinator
// E + F (F adiacent sibling of E)
else if ((match = selector.match(Patterns.adjacent))) {
source = NATIVE_TRAVERSAL_API ?
'var N' + k + '=e;if((e=e.previousElementSibling)){' + source + '}e=N' + k + ';' :
'var N' + k + '=e;while((e=e.previousSibling)){if(e.nodeType==1){' + source + 'break;}}e=N' + k + ';';
}
// *** General sibling combinator
// E ~ F (F relative sibling of E)
else if ((match = selector.match(Patterns.relative))) {
source = NATIVE_TRAVERSAL_API ?
'var N' + k + '=e;while((e=e.previousElementSibling)){' + source + '}e=N' + k + ';' :
'var N' + k + '=e;while((e=e.previousSibling)){if(e.nodeType==1){' + source + '}}e=N' + k + ';';
}
// *** Child combinator
// E > F (F children of E)
else if ((match = selector.match(Patterns.children))) {
source = 'var N' + k + '=e;if((e=e.parentNode)&&e.nodeType==1){' + source + '}e=N' + k + ';';
}
// *** Descendant combinator
// E F (E ancestor of F)
else if ((match = selector.match(Patterns.ancestor))) {
source = 'var N' + k + '=e;while((e=e.parentNode)&&e.nodeType==1){' + source + '}e=N' + k + ';';
}
// *** Structural pseudo-classes
// :root, :empty,
// :first-child, :last-child, :only-child,
// :first-of-type, :last-of-type, :only-of-type,
// :nth-child(), :nth-last-child(), :nth-of-type(), :nth-last-of-type()
else if ((match = selector.match(Patterns.spseudos)) && match[1]) {
switch (match[1]) {
case 'root':
// element root of the document
if (match[3]) {
source = 'if(e===h||s.contains(h,e)){' + source + '}';
} else {
source = 'if(e===h){' + source + '}';
}
break;
case 'empty':
// element that has no children
source = 'if(s.isEmpty(e)){' + source + '}';
break;
default:
if (match[1] && match[2]) {
if (match[2] == 'n') {
source = 'if(e!==h){' + source + '}';
break;
} else if (match[2] == 'even') {
a = 2;
b = 0;
} else if (match[2] == 'odd') {
a = 2;
b = 1;
} else {
// assumes correct "an+b" format, "b" before "a" to keep "n" values
b = ((n = match[2].match(/(-?\d+)$/)) ? parseInt(n[1], 10) : 0);
a = ((n = match[2].match(/(-?\d*)n/i)) ? parseInt(n[1], 10) : 0);
if (n && n[1] == '-') a = -1;
}
// build test expression out of structural pseudo (an+b) parameters
// see here: path_to_url#nth-child-pseudo
test = a > 1 ?
(/last/i.test(match[1])) ? '(n-(' + b + '))%' + a + '==0' :
'n>=' + b + '&&(n-(' + b + '))%' + a + '==0' : a < -1 ?
(/last/i.test(match[1])) ? '(n-(' + b + '))%' + a + '==0' :
'n<=' + b + '&&(n-(' + b + '))%' + a + '==0' : a === 0 ?
'n==' + b : a == -1 ? 'n<=' + b : 'n>=' + b;
// 4 cases: 1 (nth) x 4 (child, of-type, last-child, last-of-type)
source =
'if(e!==h){' +
'n=s[' + (/-of-type/i.test(match[1]) ? '"nthOfType"' : '"nthElement"') + ']' +
'(e,' + (/last/i.test(match[1]) ? 'true' : 'false') + ');' +
'if(' + test + '){' + source + '}' +
'}';
} else {
// 6 cases: 3 (first, last, only) x 1 (child) x 2 (-of-type)
a = /first/i.test(match[1]) ? 'previous' : 'next';
n = /only/i.test(match[1]) ? 'previous' : 'next';
b = /first|last/i.test(match[1]);
type = /-of-type/i.test(match[1]) ? '&&n.nodeName!=e.nodeName' : '&&n.nodeName<"@"';
source = 'if(e!==h){' +
( 'n=e;while((n=n.' + a + 'Sibling)' + type + ');if(!n){' + (b ? source :
'n=e;while((n=n.' + n + 'Sibling)' + type + ');if(!n){' + source + '}') + '}' ) + '}';
}
break;
}
}
// *** negation, user action and target pseudo-classes
// *** UI element states and dynamic pseudo-classes
// CSS4 :matches
// CSS3 :not, :checked, :enabled, :disabled, :target
// CSS3 :active, :hover, :focus
// CSS3 :link, :visited
else if ((match = selector.match(Patterns.dpseudos)) && match[1]) {
switch (match[1].match(/^\w+/)[0]) {
// CSS4 matches pseudo-class
case 'matches':
expr = match[3].replace(reTrimSpaces, '');
source = 'if(s.match(e, "' + expr.replace(/\x22/g, '\\"') + '",g)){' + source +'}';
break;
// CSS3 negation pseudo-class
case 'not':
// compile nested selectors, DO NOT pass the callback parameter
// SIMPLENOT allow disabling complex selectors nested
// in ':not()' pseudo-classes, breaks some test units
expr = match[3].replace(reTrimSpaces, '');
if (Config.SIMPLENOT && !reSimpleNot.test(expr)) {
// see above, log error but continue execution
emit('Negation pseudo-class only accepts simple selectors "' + selector + '"');
return '';
} else {
if ('compatMode' in doc) {
source = 'if(!' + compile(expr, '', false) + '(e,s,d,h,g)){' + source + '}';
} else {
source = 'if(!s.match(e, "' + expr.replace(/\x22/g, '\\"') + '",g)){' + source +'}';
}
}
break;
// CSS3 UI element states
case 'checked':
// for radio buttons checkboxes (HTML4) and options (HTML5)
source = 'if((typeof e.form!=="undefined"&&(/^(?:radio|checkbox)$/i).test(e.type)&&e.checked)' +
(Config.USE_HTML5 ? '||(/^option$/i.test(e.nodeName)&&(e.selected||e.checked))' : '') +
'){' + source + '}';
break;
case 'disabled':
// does not consider hidden input fields
source = 'if(((typeof e.form!=="undefined"' +
(Config.USE_HTML5 ? '' : '&&!(/^hidden$/i).test(e.type)') +
')||s.isLink(e))&&e.disabled===true){' + source + '}';
break;
case 'enabled':
// does not consider hidden input fields
source = 'if(((typeof e.form!=="undefined"' +
(Config.USE_HTML5 ? '' : '&&!(/^hidden$/i).test(e.type)') +
')||s.isLink(e))&&e.disabled===false){' + source + '}';
break;
// CSS3 lang pseudo-class
case 'lang':
test = '';
if (match[2]) test = match[2].substr(0, 2) + '-';
source = 'do{(n=e.lang||"").toLowerCase();' +
'if((n==""&&h.lang=="' + match[2].toLowerCase() + '")||' +
'(n&&(n=="' + match[2].toLowerCase() +
'"||n.substr(0,3)=="' + test.toLowerCase() + '")))' +
'{' + source + 'break;}}while((e=e.parentNode)&&e!==g);';
break;
// CSS3 target pseudo-class
case 'target':
source = 'if(e.id==d.location.hash.slice(1)){' + source + '}';
break;
// CSS3 dynamic pseudo-classes
case 'link':
source = 'if(s.isLink(e)&&!e.visited){' + source + '}';
break;
case 'visited':
source = 'if(s.isLink(e)&&e.visited){' + source + '}';
break;
// CSS3 user action pseudo-classes IE & FF3 have native support
// these capabilities may be emulated by some event managers
case 'active':
if (XML_DOCUMENT) break;
source = 'if(e===d.activeElement){' + source + '}';
break;
case 'hover':
if (XML_DOCUMENT) break;
source = 'if(e===d.hoverElement){' + source + '}';
break;
case 'focus':
if (XML_DOCUMENT) break;
source = NATIVE_FOCUS ?
'if(e===d.activeElement&&d.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number")){' + source + '}' :
'if(e===d.activeElement&&(e.type||e.href)){' + source + '}';
break;
// CSS2 selected pseudo-classes, not part of current CSS3 drafts
// the 'selected' property is only available for option elements
case 'selected':
// fix Safari selectedIndex property bug
expr = BUGGY_SELECTED ? '||(n=e.parentNode)&&n.options[n.selectedIndex]===e' : '';
source = 'if(/^option$/i.test(e.nodeName)&&(e.selected||e.checked' + expr + ')){' + source + '}';
break;
default:
break;
}
}
else if ((match = selector.match(Patterns.epseudos)) && match[1]) {
source = 'if(!(/1|11/).test(e.nodeType)){' + source + '}';
}
else {
// this is where external extensions are
// invoked if expressions match selectors
expr = false;
status = false;
for (expr in Selectors) {
if ((match = selector.match(Selectors[expr].Expression)) && match[1]) {
result = Selectors[expr].Callback(match, source);
if ('match' in result) { match = result.match; }
source = result.source;
status = result.status;
if (status) { break; }
}
}
// if an extension fails to parse the selector
// it must return a false boolean in "status"
if (!status) {
// log error but continue execution, don't throw real exceptions
// because blocking following processes maybe is not a good idea
emit('Unknown pseudo-class selector "' + selector + '"');
return '';
}
if (!expr) {
// see above, log error but continue execution
emit('Unknown token in selector "' + selector + '"');
return '';
}
}
// error if no matches found by the pattern scan
if (!match) {
emit('Invalid syntax in selector "' + selector + '"');
return '';
}
// ensure "match" is not null or empty since
// we do not throw real DOMExceptions above
selector = match && match[match.length - 1];
}
return source;
},
/*----------------------------- QUERY METHODS ------------------------------*/
// match element with selector
// @return boolean
match =
function(element, selector, from, callback) {
var parts;
if (!(element && element.nodeType == 1)) {
emit('Invalid element argument');
return false;
} else if (typeof selector != 'string') {
emit('Invalid selector argument');
return false;
} else if (from && from.nodeType == 1 && !contains(from, element)) {
return false;
} else if (lastContext !== from) {
// reset context data when it changes
// and ensure context is set to a default
switchContext(from || (from = element.ownerDocument));
}
// normalize the selector string, remove [\n\r\f]
// whitespace, replace codepoints 0 with '\ufffd'
// trim non-relevant leading/trailing whitespaces
selector = selector.
replace(reTrimSpaces, '').
replace(/\x00|\\$/g, '\ufffd');
Config.SHORTCUTS && (selector = Dom.shortcuts(selector, element, from));
if (lastMatcher != selector) {
// process valid selector strings
if ((parts = selector.match(reValidator)) && parts[0] == selector) {
isSingleMatch = (parts = selector.match(reSplitGroup)).length < 2;
// save passed selector
lastMatcher = selector;
lastPartsMatch = parts;
} else {
emit('The string "' + selector + '", is not a valid CSS selector');
return false;
}
} else parts = lastPartsMatch;
// compile matcher resolvers if necessary
if (!matchResolvers[selector] || matchContexts[selector] !== from) {
matchResolvers[selector] = compile(isSingleMatch ? [selector] : parts, '', false);
matchContexts[selector] = from;
}
return matchResolvers[selector](element, Snapshot, doc, root, from, callback);
},
// select only the first element
// matching selector (document ordered)
first =
function(selector, from) {
return select(selector, from, function() { return false; })[0] || null;
},
// select elements matching selector
// using new Query Selector API
// or cross-browser client API
// @return array
select =
function(selector, from, callback) {
var i, changed, element, elements, parts, token, original = selector;
if (arguments.length === 0) {
emit('Not enough arguments');
return [ ];
} else if (typeof selector != 'string') {
return [ ];
} else if (from && !(/1|9|11/).test(from.nodeType)) {
emit('Invalid or illegal context element');
return [ ];
} else if (lastContext !== from) {
// reset context data when it changes
// and ensure context is set to a default
switchContext(from || (from = doc));
}
if (Config.CACHING && (elements = Dom.loadResults(original, from, doc, root))) {
return callback ? concatCall([ ], elements, callback) : elements;
}
// normalize the selector string, remove [\n\r\f]
// whitespace, replace codepoints 0 with '\ufffd'
// trim non-relevant leading/trailing whitespaces
selector = selector.
replace(reTrimSpaces, '').
replace(/\x00|\\$/g, '\ufffd');
if (!OPERA_QSAPI && reSimpleSelector.test(selector)) {
switch (selector.charAt(0)) {
case '#':
if (Config.UNIQUE_ID) {
elements = (element = _byId(selector.slice(1), from)) ? [ element ] : [ ];
}
break;
case '.':
elements = _byClass(selector.slice(1), from);
break;
default:
elements = _byTag(selector, from);
break;
}
}
else if (!XML_DOCUMENT && Config.USE_QSAPI &&
!(BUGGY_QUIRKS_QSAPI && reClass.test(selector)) &&
!RE_BUGGY_QSAPI.test(selector)) {
try {
elements = from.querySelectorAll(selector);
} catch(e) { }
}
if (elements) {
elements = callback ? concatCall([ ], elements, callback) :
NATIVE_SLICE_PROTO ? slice.call(elements) : concatList([ ], elements);
Config.CACHING && Dom.saveResults(original, from, doc, elements);
return elements;
}
Config.SHORTCUTS && (selector = Dom.shortcuts(selector, from));
if ((changed = lastSelector != selector)) {
// process valid selector strings
if ((parts = selector.match(reValidator)) && parts[0] == selector) {
isSingleSelect = (parts = selector.match(reSplitGroup)).length < 2;
// save passed selector
lastSelector = selector;
lastPartsSelect = parts;
} else {
emit('The string "' + selector + '", is not a valid CSS selector');
return [ ];
}
} else parts = lastPartsSelect;
// commas separators are treated sequentially to maintain order
if (from.nodeType == 11) {
elements = byTagRaw('*', from);
} else if (!XML_DOCUMENT && isSingleSelect) {
if (changed) {
// get right most selector token
parts = selector.match(reSplitToken);
token = parts[parts.length - 1];
// only last slice before :not rules
lastSlice = token.split(':not');
lastSlice = lastSlice[lastSlice.length - 1];
// position where token was found
lastPosition = selector.length - token.length;
}
// ID optimization RTL, to reduce number of elements to visit
if (Config.UNIQUE_ID && lastSlice && (parts = lastSlice.match(Optimize.ID)) && (token = parts[1])) {
if ((element = _byId(token, from))) {
if (match(element, selector)) {
callback && callback(element);
elements = [element];
} else elements = [ ];
}
}
// ID optimization LTR, to reduce selection context searches
else if (Config.UNIQUE_ID && (parts = selector.match(Optimize.ID)) && (token = parts[1])) {
if ((element = _byId(token, doc))) {
if ('#' + token == selector) {
callback && callback(element);
elements = [element];
} else if (/[>+~]/.test(selector)) {
from = element.parentNode;
} else {
from = element;
}
} else elements = [ ];
}
if (elements) {
Config.CACHING && Dom.saveResults(original, from, doc, elements);
return elements;
}
if (!NATIVE_GEBCN && lastSlice && (parts = lastSlice.match(Optimize.TAG)) && (token = parts[1])) {
if ((elements = _byTag(token, from)).length === 0) { return [ ]; }
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace(token, '*');
}
else if (lastSlice && (parts = lastSlice.match(Optimize.CLASS)) && (token = parts[1])) {
if ((elements = _byClass(token, from)).length === 0) { return [ ]; }
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace('.' + token,
reOptimizeSelector.test(selector.charAt(selector.indexOf(token) - 1)) ? '' : '*');
}
else if ((parts = selector.match(Optimize.CLASS)) && (token = parts[1])) {
if ((elements = _byClass(token, from)).length === 0) { return [ ]; }
for (i = 0, els = [ ]; elements.length > i; ++i) {
els = concatList(els, elements[i].getElementsByTagName('*'));
}
elements = els;
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace('.' + token,
reOptimizeSelector.test(selector.charAt(selector.indexOf(token) - 1)) ? '' : '*');
}
else if (NATIVE_GEBCN && lastSlice && (parts = lastSlice.match(Optimize.TAG)) && (token = parts[1])) {
if ((elements = _byTag(token, from)).length === 0) { return [ ]; }
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace(token, '*');
}
}
if (!elements) {
if (IE_LT_9) {
elements = /^(?:applet|object)$/i.test(from.nodeName) ? from.children : byTagRaw('*', from);
} else {
elements = from.getElementsByTagName('*');
}
}
// end of prefiltering pass
// compile selector resolver if necessary
if (!selectResolvers[selector] || selectContexts[selector] !== from) {
selectResolvers[selector] = compile(isSingleSelect ? [selector] : parts, '', true);
selectContexts[selector] = from;
}
elements = selectResolvers[selector](elements, Snapshot, doc, root, from, callback);
Config.CACHING && Dom.saveResults(original, from, doc, elements);
return elements;
},
/*-------------------------------- STORAGE ---------------------------------*/
// empty function handler
FN = function(x) { return x; },
// compiled match functions returning booleans
matchContexts = { },
matchResolvers = { },
// compiled select functions returning collections
selectContexts = { },
selectResolvers = { },
// used to pass methods to compiled functions
Snapshot = {
// element indexing methods
nthElement: nthElement,
nthOfType: nthOfType,
// element inspection methods
getAttribute: getAttribute,
hasAttribute: hasAttribute,
// element selection methods
byClass: _byClass,
byName: byName,
byTag: _byTag,
byId: _byId,
// helper/check methods
contains: contains,
isEmpty: isEmpty,
isLink: isLink,
// selection/matching
select: select,
match: match
},
/*------------------------------- PUBLIC API -------------------------------*/
// code referenced by extensions
Dom = {
ACCEPT_NODE: ACCEPT_NODE,
// retrieve element by id attr
byId: byId,
// retrieve elements by tag name
byTag: byTag,
// retrieve elements by name attr
byName: byName,
// retrieve elements by class name
byClass: byClass,
// read the value of the attribute
// as was in the original HTML code
getAttribute: getAttribute,
// check for the attribute presence
// as was in the original HTML code
hasAttribute: hasAttribute,
// element match selector, return boolean true/false
match: match,
// first element match only, return element or null
first: first,
// elements matching selector, starting from element
select: select,
// compile selector into ad-hoc javascript resolver
compile: compile,
// check that two elements are ancestor/descendant
contains: contains,
// handle selector engine configuration settings
configure: configure,
// initialize caching for each document
setCache: FN,
// load previously collected result set
loadResults: FN,
// save previously collected result set
saveResults: FN,
// handle missing context in selector strings
shortcuts: FN,
// log resolvers errors/warnings
emit: emit,
// options enabing specific engine functionality
Config: Config,
// pass methods references to compiled resolvers
Snapshot: Snapshot,
// operators descriptor
// for attribute operators extensions
Operators: Operators,
// selectors descriptor
// for pseudo-class selectors extensions
Selectors: Selectors,
// export validators REs
Tokens: Tokens,
// export version string
Version: version,
// add or overwrite user defined operators
registerOperator:
function(symbol, resolver) {
Operators[symbol] || (Operators[symbol] = resolver);
},
// add selector patterns for user defined callbacks
registerSelector:
function(name, rexp, func) {
Selectors[name] || (Selectors[name] = {
Expression: rexp,
Callback: func
});
}
};
/*---------------------------------- INIT ----------------------------------*/
// init context specific variables
initialize(doc);
return Dom;
});
``` | /content/code_sandbox/node_modules/nwmatcher/src/nwmatcher.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 15,524 |
```javascript
/*
* All rights reserved.
*
* nwmatcher-base.js - A fast CSS selector engine and matcher
*
* Author: Diego Perini <diego.perini at gmail com>
* Version: 1.4.4
* Created: 20070722
* Release: 20180305
*
* path_to_url
* Download:
* path_to_url
*/
(function(global, factory) {
if (typeof module == 'object' && typeof exports == 'object') {
module.exports = factory;
} else if (typeof define === 'function' && define["amd"]) {
define(factory);
} else {
global.NW || (global.NW = { });
global.NW.Dom = factory(global);
}
})(this, function(global) {
var version = 'nwmatcher-1.4.4',
doc = global.document,
root = doc.documentElement,
isSingleMatch,
isSingleSelect,
lastSlice,
lastContext,
lastPosition,
lastMatcher,
lastSelector,
lastPartsMatch,
lastPartsSelect,
prefixes = '(?:[#.:]|::)?',
operators = '([~*^$|!]?={1})',
whitespace = '[\\x20\\t\\n\\r\\f]',
combinators = '\\x20|[>+~](?=[^>+~])',
pseudoparms = '(?:[-+]?\\d*n)?[-+]?\\d*',
skip_groups = '\\[.*\\]|\\(.*\\)|\\{.*\\}',
any_esc_chr = '\\\\.',
alphalodash = '[_a-zA-Z]',
non_asc_chr = '[^\\x00-\\x9f]',
escaped_chr = '\\\\[^\\n\\r\\f0-9a-fA-F]',
unicode_chr = '\\\\[0-9a-fA-F]{1,6}(?:\\r\\n|' + whitespace + ')?',
quotedvalue = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"' + "|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'",
reSplitGroup = /([^,\\()[\]]+|\[[^[\]]*\]|\[.*\]|\([^()]+\)|\(.*\)|\{[^{}]+\}|\{.*\}|\\.)+/g,
reTrimSpaces = RegExp('[\\n\\r\\f]|^' + whitespace + '+|' + whitespace + '+$', 'g'),
reEscapedChars = /\\([0-9a-fA-F]{1,6}[\x20\t\n\r\f]?|.)|([\x22\x27])/g,
standardValidator, extendedValidator, reValidator,
attrcheck, attributes, attrmatcher, pseudoclass,
reOptimizeSelector, reSimpleNot, reSplitToken,
Optimize, identifier, extensions = '.+',
Patterns = {
children: RegExp('^' + whitespace + '*\\>' + whitespace + '*(.*)'),
adjacent: RegExp('^' + whitespace + '*\\+' + whitespace + '*(.*)'),
relative: RegExp('^' + whitespace + '*\\~' + whitespace + '*(.*)'),
ancestor: RegExp('^' + whitespace + '+(.*)'),
universal: RegExp('^\\*(.*)')
},
Tokens = {
prefixes: prefixes,
identifier: identifier,
attributes: attributes
},
QUIRKS_MODE,
XML_DOCUMENT,
GEBTN = 'getElementsByTagName' in doc,
GEBCN = 'getElementsByClassName' in doc,
IE_LT_9 = typeof doc.addEventListener != 'function',
LINK_NODES = { a: 1, A: 1, area: 1, AREA: 1, link: 1, LINK: 1 },
ATTR_BOOLEAN = {
checked: 1, disabled: 1, ismap: 1,
multiple: 1, readonly: 1, selected: 1
},
ATTR_DEFAULT = {
value: 'defaultValue',
checked: 'defaultChecked',
selected: 'defaultSelected'
},
ATTR_URIDATA = {
action: 2, cite: 2, codebase: 2, data: 2, href: 2,
longdesc: 2, lowsrc: 2, src: 2, usemap: 2
},
HTML_TABLE = {
'accept': 1, 'accept-charset': 1, 'align': 1, 'alink': 1, 'axis': 1,
'bgcolor': 1, 'charset': 1, 'checked': 1, 'clear': 1, 'codetype': 1, 'color': 1,
'compact': 1, 'declare': 1, 'defer': 1, 'dir': 1, 'direction': 1, 'disabled': 1,
'enctype': 1, 'face': 1, 'frame': 1, 'hreflang': 1, 'http-equiv': 1, 'lang': 1,
'language': 1, 'link': 1, 'media': 1, 'method': 1, 'multiple': 1, 'nohref': 1,
'noresize': 1, 'noshade': 1, 'nowrap': 1, 'readonly': 1, 'rel': 1, 'rev': 1,
'rules': 1, 'scope': 1, 'scrolling': 1, 'selected': 1, 'shape': 1, 'target': 1,
'text': 1, 'type': 1, 'valign': 1, 'valuetype': 1, 'vlink': 1
},
NATIVE_TRAVERSAL_API =
'nextElementSibling' in root &&
'previousElementSibling' in root,
Selectors = { },
Operators = {
'=': "n=='%m'",
'^=': "n.indexOf('%m')==0",
'*=': "n.indexOf('%m')>-1",
'|=': "(n+'-').indexOf('%m-')==0",
'~=': "(' '+n+' ').indexOf(' %m ')>-1",
'$=': "n.substr(n.length-'%m'.length)=='%m'"
},
concatCall =
function(data, elements, callback) {
var i = -1, element;
while ((element = elements[++i])) {
if (false === callback(data[data.length] = element)) { break; }
}
return data;
},
switchContext =
function(from, force) {
var oldDoc = doc;
lastContext = from;
doc = from.ownerDocument || from;
if (force || oldDoc !== doc) {
root = doc.documentElement;
XML_DOCUMENT = doc.createElement('DiV').nodeName == 'DiV';
QUIRKS_MODE = !XML_DOCUMENT &&
typeof doc.compatMode == 'string' ?
doc.compatMode.indexOf('CSS') < 0 :
(function() {
var style = doc.createElement('div').style;
return style && (style.width = 1) && style.width == '1px';
})();
Config.CACHING && Dom.setCache(true, doc);
}
},
codePointToUTF16 =
function(codePoint) {
if (codePoint < 1 || codePoint > 0x10ffff ||
(codePoint > 0xd7ff && codePoint < 0xe000)) {
return '\\ufffd';
}
if (codePoint < 0x10000) {
var lowHex = '000' + codePoint.toString(16);
return '\\u' + lowHex.substr(lowHex.length - 4);
}
return '\\u' + (((codePoint - 0x10000) >> 0x0a) + 0xd800).toString(16) +
'\\u' + (((codePoint - 0x10000) % 0x400) + 0xdc00).toString(16);
},
stringFromCodePoint =
function(codePoint) {
if (codePoint < 1 || codePoint > 0x10ffff ||
(codePoint > 0xd7ff && codePoint < 0xe000)) {
return '\ufffd';
}
if (codePoint < 0x10000) {
return String.fromCharCode(codePoint);
}
return String.fromCodePoint ?
String.fromCodePoint(codePoint) :
String.fromCharCode(
((codePoint - 0x10000) >> 0x0a) + 0xd800,
((codePoint - 0x10000) % 0x400) + 0xdc00);
},
convertEscapes =
function(str) {
return str.replace(reEscapedChars,
function(substring, p1, p2) {
return p2 ? '\\' + p2 :
(/^[0-9a-fA-F]/).test(p1) ? codePointToUTF16(parseInt(p1, 16)) :
(/^[\\\x22\x27]/).test(p1) ? substring :
p1;
}
);
},
unescapeIdentifier =
function(str) {
return str.replace(reEscapedChars,
function(substring, p1, p2) {
return p2 ? p2 :
(/^[0-9a-fA-F]/).test(p1) ? stringFromCodePoint(parseInt(p1, 16)) :
(/^[\\\x22\x27]/).test(p1) ? substring :
p1;
}
);
},
byIdRaw =
function(id, elements) {
var i = -1, element;
while ((element = elements[++i])) {
if (element.getAttribute('id') == id) {
break;
}
}
return element || null;
},
_byId = !IE_LT_9 ?
function(id, from) {
id = (/\\/).test(id) ? unescapeIdentifier(id) : id;
return from.getElementById && from.getElementById(id) ||
byIdRaw(id, from.getElementsByTagName('*'));
} :
function(id, from) {
var element = null;
id = (/\\/).test(id) ? unescapeIdentifier(id) : id;
if (XML_DOCUMENT || from.nodeType != 9) {
return byIdRaw(id, from.getElementsByTagName('*'));
}
if ((element = from.getElementById(id)) &&
element.name == id && from.getElementsByName) {
return byIdRaw(id, from.getElementsByName(id));
}
return element;
},
byId =
function(id, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byId(id, from);
},
byTagRaw =
function(tag, from) {
var any = tag == '*', element = from, elements = [ ], next = element.firstChild;
any || (tag = tag.toUpperCase());
while ((element = next)) {
if (element.tagName > '@' && (any || element.tagName.toUpperCase() == tag)) {
elements[elements.length] = element;
}
if ((next = element.firstChild || element.nextSibling)) continue;
while (!next && (element = element.parentNode) && element !== from) {
next = element.nextSibling;
}
}
return elements;
},
getAttribute = !IE_LT_9 ?
function(node, attribute) {
return node.getAttribute(attribute);
} :
function(node, attribute) {
attribute = attribute.toLowerCase();
if (typeof node[attribute] == 'object') {
return node.attributes[attribute] &&
node.attributes[attribute].value;
}
return (
attribute == 'type' ? node.getAttribute(attribute) :
ATTR_URIDATA[attribute] ? node.getAttribute(attribute, 2) :
ATTR_BOOLEAN[attribute] ? node.getAttribute(attribute) ? attribute : 'false' :
(node = node.getAttributeNode(attribute)) && node.value);
},
hasAttribute = !IE_LT_9 && root.hasAttribute ?
function(node, attribute) {
return node.hasAttribute(attribute);
} :
function(node, attribute) {
var obj = node.getAttributeNode(attribute = attribute.toLowerCase());
return ATTR_DEFAULT[attribute] && attribute != 'value' ?
node[ATTR_DEFAULT[attribute]] : obj && obj.specified;
},
configure =
function(option) {
if (typeof option == 'string') { return !!Config[option]; }
if (typeof option != 'object') { return Config; }
for (var i in option) {
Config[i] = !!option[i];
if (i == 'SIMPLENOT') {
matchContexts = { };
matchResolvers = { };
selectContexts = { };
selectResolvers = { };
}
}
setIdentifierSyntax();
reValidator = RegExp(Config.SIMPLENOT ?
standardValidator : extendedValidator);
return true;
},
emit =
function(message) {
if (Config.VERBOSITY) { throw Error(message); }
if (Config.LOGERRORS && console && console.log) {
console.log(message);
}
},
Config = {
CACHING: false,
ESCAPECHR: true,
NON_ASCII: true,
SELECTOR3: true,
UNICODE16: true,
SHORTCUTS: false,
SIMPLENOT: true,
SVG_LCASE: false,
UNIQUE_ID: true,
USE_HTML5: true,
VERBOSITY: true,
LOGERRORS: true
},
initialize =
function(doc) {
setIdentifierSyntax();
switchContext(doc, true);
},
setIdentifierSyntax =
function() {
var syntax = '', start = Config['SELECTOR3'] ? '-{2}|' : '';
Config['NON_ASCII'] && (syntax += '|' + non_asc_chr);
Config['UNICODE16'] && (syntax += '|' + unicode_chr);
Config['ESCAPECHR'] && (syntax += '|' + escaped_chr);
syntax += (Config['UNICODE16'] || Config['ESCAPECHR']) ? '' : '|' + any_esc_chr;
identifier = '-?(?:' + start + alphalodash + syntax + ')(?:-|[0-9]|' + alphalodash + syntax + ')*';
attrcheck = '(' + quotedvalue + '|' + identifier + ')';
attributes = whitespace + '*(' + identifier + '(?::' + identifier + ')?)' +
whitespace + '*(?:' + operators + whitespace + '*' + attrcheck + ')?' + whitespace + '*' + '(i)?' + whitespace + '*';
attrmatcher = attributes.replace(attrcheck, '([\\x22\\x27]*)((?:\\\\?.)*?)\\3');
pseudoclass = '((?:' +
pseudoparms + '|' + quotedvalue + '|' +
prefixes + identifier + '|' +
'\\[' + attributes + '\\]|' +
'\\(.+\\)|' + whitespace + '*|' +
',)+)';
standardValidator =
'(?=[\\x20\\t\\n\\r\\f]*[^>+~(){}<>])' +
'(' +
'\\*' +
'|(?:' + prefixes + identifier + ')' +
'|' + combinators +
'|\\[' + attributes + '\\]' +
'|\\(' + pseudoclass + '\\)' +
'|\\{' + extensions + '\\}' +
'|(?:,|' + whitespace + '*)' +
')+';
reSimpleNot = RegExp('^(' +
'(?!:not)' +
'(' + prefixes + identifier +
'|\\([^()]*\\))+' +
'|\\[' + attributes + '\\]' +
')$');
reSplitToken = RegExp('(' +
prefixes + identifier + '|' +
'\\[' + attributes + '\\]|' +
'\\(' + pseudoclass + '\\)|' +
'\\\\.|[^\\x20\\t\\n\\r\\f>+~])+', 'g');
reOptimizeSelector = RegExp(identifier + '|^$');
Optimize = {
ID: RegExp('^\\*?#(' + identifier + ')|' + skip_groups),
TAG: RegExp('^(' + identifier + ')|' + skip_groups),
CLASS: RegExp('^\\.(' + identifier + '$)|' + skip_groups)
};
Patterns.id = RegExp('^#(' + identifier + ')(.*)');
Patterns.tagName = RegExp('^(' + identifier + ')(.*)');
Patterns.className = RegExp('^\\.(' + identifier + ')(.*)');
Patterns.attribute = RegExp('^\\[' + attrmatcher + '\\](.*)');
Tokens.identifier = identifier;
Tokens.attributes = attributes;
extendedValidator = standardValidator.replace(pseudoclass, '.*');
reValidator = RegExp(standardValidator);
},
ACCEPT_NODE = 'r[r.length]=c[k];if(f&&false===f(c[k]))break main;else continue main;',
REJECT_NODE = IE_LT_9 ? 'if(e.nodeName<"A")continue;' : '',
TO_UPPER_CASE = IE_LT_9 ? '.toUpperCase()' : '',
compile =
function(selector, source, mode) {
var parts = typeof selector == 'string' ? selector.match(reSplitGroup) : selector;
typeof source == 'string' || (source = '');
if (parts.length == 1) {
source += compileSelector(parts[0], mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
} else {
var i = -1, seen = { }, token;
while ((token = parts[++i])) {
token = token.replace(reTrimSpaces, '');
if (!seen[token] && (seen[token] = true)) {
source += compileSelector(token, mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
}
}
}
if (mode) {
return Function('c,s,d,h,g,f',
'var N,n,x=0,k=-1,e,r=[];main:while((e=c[++k])){' + source + '}return r;');
} else {
return Function('e,s,d,h,g,f',
'var N,n,x=0,k=e;' + source + 'return false;');
}
},
compileSelector =
function(selector, source, mode) {
var k = 0, expr, match, result, status, test, type;
while (selector) {
k++;
if ((match = selector.match(Patterns.universal))) {
expr = '';
}
else if ((match = selector.match(Patterns.id))) {
match[1] = (/\\/).test(match[1]) ? convertEscapes(match[1]) : match[1];
source = 'if(' + (XML_DOCUMENT ?
's.getAttribute(e,"id")' :
'(e.submit?s.getAttribute(e,"id"):e.id)') +
'=="' + match[1] + '"' +
'){' + source + '}';
}
else if ((match = selector.match(Patterns.tagName))) {
test = Config.SVG_LCASE ? '||e.nodeName=="' + match[1].toLowerCase() + '"' : '';
source = 'if(e.nodeName' + (XML_DOCUMENT ?
'=="' + match[1] + '"' : TO_UPPER_CASE +
'=="' + match[1].toUpperCase() + '"' + test) +
'){' + source + '}';
}
else if ((match = selector.match(Patterns.className))) {
match[1] = (/\\/).test(match[1]) ? convertEscapes(match[1]) : match[1];
match[1] = QUIRKS_MODE ? match[1].toLowerCase() : match[1];
source = 'if((n=' + (XML_DOCUMENT ?
'e.getAttribute("class")' : 'e.className') +
')&&n.length&&(" "+' + (QUIRKS_MODE ? 'n.toLowerCase()' : 'n') +
'.replace(/' + whitespace + '+/g," ")+" ").indexOf(" ' + match[1] + ' ")>-1' +
'){' + source + '}';
}
else if ((match = selector.match(Patterns.attribute))) {
expr = match[1].split(':');
expr = expr.length == 2 ? expr[1] : expr[0] + '';
if (match[2] && !Operators[match[2]]) {
emit('Unsupported operator in attribute selectors "' + selector + '"');
return '';
}
test = 'false';
if (match[2] && match[4] && (test = Operators[match[2]])) {
match[4] = (/\\/).test(match[4]) ? convertEscapes(match[4]) : match[4];
type = match[5] == 'i' || HTML_TABLE[expr.toLowerCase()];
test = test.replace(/\%m/g, type ? match[4].toLowerCase() : match[4]);
} else if (match[2] == '!=' || match[2] == '=') {
test = 'n' + match[2] + '=""';
}
source = 'if(n=s.hasAttribute(e,"' + match[1] + '")){' +
(match[2] ? 'n=s.getAttribute(e,"' + match[1] + '")' : '') +
(type && match[2] ? '.toLowerCase();' : ';') +
'if(' + (match[2] ? test : 'n') + '){' + source + '}}';
}
else if ((match = selector.match(Patterns.adjacent))) {
source = NATIVE_TRAVERSAL_API ?
'var N' + k + '=e;if((e=e.previousElementSibling)){' + source + '}e=N' + k + ';' :
'var N' + k + '=e;while((e=e.previousSibling)){if(e.nodeType==1){' + source + 'break;}}e=N' + k + ';';
}
else if ((match = selector.match(Patterns.relative))) {
source = NATIVE_TRAVERSAL_API ?
'var N' + k + '=e;while((e=e.previousElementSibling)){' + source + '}e=N' + k + ';' :
'var N' + k + '=e;while((e=e.previousSibling)){if(e.nodeType==1){' + source + '}}e=N' + k + ';';
}
else if ((match = selector.match(Patterns.children))) {
source = 'var N' + k + '=e;if((e=e.parentNode)&&e.nodeType==1){' + source + '}e=N' + k + ';';
}
else if ((match = selector.match(Patterns.ancestor))) {
source = 'var N' + k + '=e;while((e=e.parentNode)&&e.nodeType==1){' + source + '}e=N' + k + ';';
}
else {
expr = false;
status = false;
for (expr in Selectors) {
if ((match = selector.match(Selectors[expr].Expression)) && match[1]) {
result = Selectors[expr].Callback(match, source);
if ('match' in result) { match = result.match; }
source = result.source;
status = result.status;
if (status) { break; }
}
}
if (!status) {
emit('Unknown pseudo-class selector "' + selector + '"');
return '';
}
if (!expr) {
emit('Unknown token in selector "' + selector + '"');
return '';
}
}
if (!match) {
emit('Invalid syntax in selector "' + selector + '"');
return '';
}
selector = match && match[match.length - 1];
}
return source;
},
match =
function(element, selector, from, callback) {
var parts;
if (!(element && element.nodeType == 1)) {
emit('Invalid element argument');
return false;
} else if (typeof selector != 'string') {
emit('Invalid selector argument');
return false;
} else if (lastContext !== from) {
switchContext(from || (from = element.ownerDocument));
}
selector = selector.
replace(reTrimSpaces, '').
replace(/\x00|\\$/g, '\ufffd');
Config.SHORTCUTS && (selector = Dom.shortcuts(selector, element, from));
if (lastMatcher != selector) {
if ((parts = selector.match(reValidator)) && parts[0] == selector) {
isSingleMatch = (parts = selector.match(reSplitGroup)).length < 2;
lastMatcher = selector;
lastPartsMatch = parts;
} else {
emit('The string "' + selector + '", is not a valid CSS selector');
return false;
}
} else parts = lastPartsMatch;
if (!matchResolvers[selector] || matchContexts[selector] !== from) {
matchResolvers[selector] = compile(isSingleMatch ? [selector] : parts, '', false);
matchContexts[selector] = from;
}
return matchResolvers[selector](element, Snapshot, doc, root, from, callback);
},
first =
function(selector, from) {
return select(selector, from, function() { return false; })[0] || null;
},
select =
function(selector, from, callback) {
var i, changed, element, elements, parts, token, original = selector;
if (arguments.length === 0) {
emit('Not enough arguments');
return [ ];
} else if (typeof selector != 'string') {
return [ ];
} else if (from && !(/1|9|11/).test(from.nodeType)) {
emit('Invalid or illegal context element');
return [ ];
} else if (lastContext !== from) {
switchContext(from || (from = doc));
}
if (Config.CACHING && (elements = Dom.loadResults(original, from, doc, root))) {
return callback ? concatCall([ ], elements, callback) : elements;
}
selector = selector.
replace(reTrimSpaces, '').
replace(/\x00|\\$/g, '\ufffd');
Config.SHORTCUTS && (selector = Dom.shortcuts(selector, from));
if ((changed = lastSelector != selector)) {
if ((parts = selector.match(reValidator)) && parts[0] == selector) {
isSingleSelect = (parts = selector.match(reSplitGroup)).length < 2;
lastSelector = selector;
lastPartsSelect = parts;
} else {
emit('The string "' + selector + '", is not a valid CSS selector');
return [ ];
}
} else parts = lastPartsSelect;
if (from.nodeType == 11) {
elements = byTagRaw('*', from);
} else if (isSingleSelect) {
if (changed) {
parts = selector.match(reSplitToken);
token = parts[parts.length - 1];
lastSlice = token.split(':not');
lastSlice = lastSlice[lastSlice.length - 1];
lastPosition = selector.length - token.length;
}
if (Config.UNIQUE_ID && lastSlice && (parts = lastSlice.match(Optimize.ID)) && (token = parts[1])) {
if ((element = _byId(token, from))) {
if (match(element, selector)) {
callback && callback(element);
elements = [element];
} else elements = [ ];
}
}
else if (Config.UNIQUE_ID && (parts = selector.match(Optimize.ID)) && (token = parts[1])) {
if ((element = _byId(token, doc))) {
if ('#' + token == selector) {
callback && callback(element);
elements = [element];
} else if (/[>+~]/.test(selector)) {
from = element.parentNode;
} else {
from = element;
}
} else elements = [ ];
}
if (elements) {
Config.CACHING && Dom.saveResults(original, from, doc, elements);
return elements;
}
if (!XML_DOCUMENT && GEBTN && lastSlice && (parts = lastSlice.match(Optimize.TAG)) && (token = parts[1])) {
if ((elements = from.getElementsByTagName(token)).length === 0) { return [ ]; }
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace(token, '*');
}
else if (!XML_DOCUMENT && GEBCN && lastSlice && (parts = lastSlice.match(Optimize.CLASS)) && (token = parts[1])) {
if ((elements = from.getElementsByClassName(unescapeIdentifier(token))).length === 0) { return [ ]; }
selector = selector.slice(0, lastPosition) + selector.slice(lastPosition).replace('.' + token,
reOptimizeSelector.test(selector.charAt(selector.indexOf(token) - 1)) ? '' : '*');
}
}
if (!elements) {
if (IE_LT_9) {
elements = /^(?:applet|object)$/i.test(from.nodeName) ? from.children : byTagRaw('*', from);
} else {
elements = from.getElementsByTagName('*');
}
}
if (!selectResolvers[selector] || selectContexts[selector] !== from) {
selectResolvers[selector] = compile(isSingleSelect ? [selector] : parts, REJECT_NODE, true);
selectContexts[selector] = from;
}
elements = selectResolvers[selector](elements, Snapshot, doc, root, from, callback);
Config.CACHING && Dom.saveResults(original, from, doc, elements);
return elements;
},
FN = function(x) { return x; },
matchContexts = { },
matchResolvers = { },
selectContexts = { },
selectResolvers = { },
Snapshot = {
byId: _byId,
match: match,
select: select,
getAttribute: getAttribute,
hasAttribute: hasAttribute
},
Dom = {
ACCEPT_NODE: ACCEPT_NODE,
byId: byId,
match: match,
first: first,
select: select,
compile: compile,
configure: configure,
setCache: FN,
shortcuts: FN,
loadResults: FN,
saveResults: FN,
emit: emit,
Config: Config,
Snapshot: Snapshot,
Operators: Operators,
Selectors: Selectors,
Tokens: Tokens,
Version: version,
registerOperator:
function(symbol, resolver) {
Operators[symbol] || (Operators[symbol] = resolver);
},
registerSelector:
function(name, rexp, func) {
Selectors[name] || (Selectors[name] = {
Expression: rexp,
Callback: func
});
}
};
initialize(doc);
return Dom;
});
``` | /content/code_sandbox/node_modules/nwmatcher/src/nwmatcher-base.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 6,709 |
```javascript
/*
* All rights reserved.
*
* this is just a small example to show
* how an extension for NWMatcher could be
* adapted to handle special jQuery selectors
*
* Child Selectors
* :even, :odd, :eq, :lt, :gt, :first, :last, :nth
*
* Pseudo Selectors
* :has, :button, :header, :input, :checkbox, :radio, :file, :image
* :password, :reset, :submit, :text, :hidden, :visible, :parent
*
*/
// for structural pseudo-classes extensions
NW.Dom.registerSelector(
'jquery:child',
/^\:((?:(nth|eq|lt|gt)\(([^()]*)\))|(?:even|odd|first|last))(.*)/i,
(function(global) {
return function(match, source, selector) {
var status = true, ACCEPT_NODE = NW.Dom.ACCEPT_NODE;
switch (match[1].toLowerCase()) {
case 'odd':
source = source.replace(ACCEPT_NODE, 'if((x=x^1)==0){' + ACCEPT_NODE + '}');
break;
case 'even':
source = source.replace(ACCEPT_NODE, 'if((x=x^1)==1){' + ACCEPT_NODE + '}');
break;
case 'first':
source = 'n=h.getElementsByTagName(e.nodeName);if(n.length&&n[0]===e){' + source + '}';
break;
case 'last':
source = 'n=h.getElementsByTagName(e.nodeName);if(n.length&&n[n.length-1]===e){' + source + '}';
break;
default:
switch (match[2].toLowerCase()) {
case 'nth':
source = 'n=h.getElementsByTagName(e.nodeName);if(n.length&&n[' + match[3] + ']===e){' + source + '}';
break;
case 'eq':
source = source.replace(ACCEPT_NODE, 'if(x++==' + match[3] + '){' + ACCEPT_NODE + '}');
break;
case 'lt':
source = source.replace(ACCEPT_NODE, 'if(x++<' + match[3] + '){' + ACCEPT_NODE + '}');
break;
case 'gt':
source = source.replace(ACCEPT_NODE, 'if(x++>' + match[3] + '){' + ACCEPT_NODE + '}');
break;
default:
status = false;
break;
}
break;
}
// compiler will add this to "source"
return {
'source': source,
'status': status
};
};
})(this));
// for element pseudo-classes extensions
NW.Dom.registerSelector(
'jquery:pseudo',
/^\:(has|checkbox|file|image|password|radio|reset|submit|text|button|input|header|hidden|visible|parent)(?:\(\s*(["']*)?([^'"()]*)\2\s*\))?(.*)/i,
(function(global) {
return function(match, source) {
var status = true, ACCEPT_NODE = NW.Dom.ACCEPT_NODE;
switch(match[1].toLowerCase()) {
case 'has':
source = source.replace(ACCEPT_NODE, 'if(e.getElementsByTagName("' + match[3].replace(/^\s|\s$/g, '') + '")[0]){' + ACCEPT_NODE + '}');
break;
case 'checkbox':
case 'file':
case 'image':
case 'password':
case 'radio':
case 'reset':
case 'submit':
case 'text':
// :checkbox, :file, :image, :password, :radio, :reset, :submit, :text
source = 'if(/^' + match[1] + '$/i.test(e.type)){' + source + '}';
break;
case 'button':
case 'input':
source = 'if(e.type||/button/i.test(e.nodeName)){' + source + '}';
break;
case 'header':
source = 'if(/h[1-6]/i.test(e.nodeName)){' + source + '}';
break;
case 'hidden':
source = 'if(!e.offsetWidth&&!e.offsetHeight){' + source + '}';
break;
case 'visible':
source = 'if(e.offsetWidth||e.offsetHeight){' + source + '}';
break;
case 'parent':
source += 'if(e.firstChild){' + source + '}';
break;
default:
status = false;
break;
}
// compiler will add this to "source"
return {
'source': source,
'status': status
};
};
})(this));
``` | /content/code_sandbox/node_modules/nwmatcher/src/modules/nwmatcher-jquery.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,004 |
```javascript
/*
* All rights reserved.
*
* this is just a small example to show
* how an extension for NWMatcher could be
* adapted to handle WebForms/HTML5 selectors
*
* Pseudo Selectors
* :default, :indeterminate, :optional, :required,
* :valid, :invalid, :in-range, :out-of-range,
* :read-only, :read-write
* :has, :matches (not yet in a defined specification)
*
*/
// for UI pseudo-classes extensions (WebForms/HTML5)
NW.Dom.registerSelector(
'html5:pseudos',
/^\:(default|indeterminate|optional|required|valid|invalid|in-range|out-of-range|read-only|read-write)(.*)/,
(function(global) {
return function(match, source) {
var status = true,
HTML5PseudoClasses = {
'default': 4, 'indeterminate': 4, 'invalid': 4, 'valid': 4,
'optional': 4, 'required': 4, 'read-write': 4, 'read-only': 4
};
switch (match[1]) {
// HTML5 UI element states (form controls)
case 'default':
// only radio buttons, check boxes and option elements
source = 'if(((typeof e.form!=="undefined"&&(/radio|checkbox/i).test(e.type))||/option/i.test(e.nodeName))&&(e.defaultChecked||e.defaultSelected)){' + source + '}';
break;
case 'indeterminate':
// only radio buttons, check boxes and option elements
source = 'if(typeof e.form!=="undefined"&&(/radio|checkbox/i).test(e.type)&&s.select("[checked]",e.form).length===0){' + source + '}';
break;
case 'optional':
// only fields for which "required" applies
source = 'if(typeof e.form!=="undefined"&&typeof e.required!="undefined"&&!e.required){' + source + '}';
break;
case 'required':
// only fields for which "required" applies
source = 'if(typeof e.form!=="undefined"&&typeof e.required!="undefined"&&e.required){' + source + '}';
break;
case 'read-write':
// only fields for which "readOnly" applies
source = 'if(typeof e.form!=="undefined"&&typeof e.readOnly!="undefined"&&!e.readOnly){' + source + '}';
break;
case 'read-only':
// only fields for which "readOnly" applies
source = 'if(typeof e.form!=="undefined"&&typeof e.readOnly!="undefined"&&e.readOnly){' + source + '}';
break;
case 'invalid':
// only fields for which validity applies
source = 'if(typeof e.form!=="undefined"&&typeof e.validity=="object"&&!e.validity.valid){' + source + '}';
break;
case 'valid':
// only fields for which validity applies
source = 'if(typeof e.form!=="undefined"&&typeof e.validity=="object"&&e.validity.valid){' + source + '}';
break;
case 'in-range':
// only fields for which validity applies
source = 'if(typeof e.form!=="undefined"&&' +
'(s.getAttribute(e,"min")||s.getAttribute(e,"max"))&&' +
'typeof e.validity=="object"&&!e.validity.typeMismatch&&' +
'!e.validity.rangeUnderflow&&!e.validity.rangeOverflow){' + source + '}';
break;
case 'out-of-range':
// only fields for which validity applies
source = 'if(typeof e.form!=="undefined"&&' +
'(s.getAttribute(e,"min")||s.getAttribute(e,"max"))&&' +
'typeof e.validity=="object"&&(e.validity.rangeUnderflow||e.validity.rangeOverflow)){' + source + '}';
break;
default:
status = false;
break;
}
// compiler will add this to "source"
return {
'source': source,
'status': status
};
};
})(this));
``` | /content/code_sandbox/node_modules/nwmatcher/src/modules/nwmatcher-webforms.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 892 |
```javascript
/*
* All rights reserved.
*
* Caching/memoization module for NWMatcher
*
* Added capabilities:
*
* - Mutation Events are feature tested and used safely
* - handle caching different document types HTML/XML/SVG
* - store result sets for different selectors / contexts
* - simultaneously control mutation on multiple documents
*
*/
(function(global) {
// export the public API for CommonJS implementations,
// for headless JS engines or for standard web browsers
var Dom =
// as CommonJS/NodeJS module
typeof exports == 'object' ? exports :
// create or extend NW namespace
((global.NW || (global.NW = { })) &&
(global.NW.Dom || (global.NW.Dom = { }))),
Contexts = { },
Results = { },
isEnabled = false,
isExpired = true,
isPaused = false,
context = global.document,
root = context.documentElement,
// timing pauses
now = 0,
// last time cache initialization was called
lastCalled = 0,
// minimum time allowed between calls to the cache initialization
minCacheRest = 15, //ms
mutationTest =
function(type, callback) {
var isSupported = false,
root = document.documentElement,
div = document.createElement('div'),
handler = function() { isSupported = true; };
root.insertBefore(div, root.firstChild);
div.addEventListener(type, handler, true);
if (callback && callback.call) callback(div);
div.removeEventListener(type, handler, true);
root.removeChild(div);
return isSupported;
},
// check for Mutation Events, DOMAttrModified should be
// enough to ensure DOMNodeInserted/DOMNodeRemoved exist
HACKED_MUTATION_EVENTS = false,
NATIVE_MUTATION_EVENTS = root.addEventListener ?
mutationTest('DOMAttrModified', function(e) { e.setAttribute('id', 'nw'); }) : false,
loadResults =
function(selector, from, doc, root) {
if (isEnabled && !isPaused) {
if (!isExpired) {
if (Results[selector] && Contexts[selector] === from) {
return Results[selector];
}
} else {
// pause caching while we are getting
// hammered by dom mutations (jdalton)
now = (new Date).getTime();
if ((now - lastCalled) < minCacheRest) {
isPaused = isExpired = true;
setTimeout(function() { isPaused = false; }, minCacheRest);
} else setCache(true, doc);
lastCalled = now;
}
}
return undefined;
},
saveResults =
function(selector, from, doc, data) {
Contexts[selector] = from;
Results[selector] = data;
return;
},
/*-------------------------------- CACHING ---------------------------------*/
// invoked by mutation events to expire cached parts
mutationWrapper =
function(event) {
var d = event.target.ownerDocument || event.target;
stopMutation(d);
expireCache(d);
},
// append mutation events
startMutation =
function(d) {
if (!d.isCaching && d.addEventListener) {
// FireFox/Opera/Safari/KHTML have support for Mutation Events
d.addEventListener('DOMAttrModified', mutationWrapper, true);
d.addEventListener('DOMNodeInserted', mutationWrapper, true);
d.addEventListener('DOMNodeRemoved', mutationWrapper, true);
d.isCaching = true;
}
},
// remove mutation events
stopMutation =
function(d) {
if (d.isCaching && d.removeEventListener) {
d.removeEventListener('DOMAttrModified', mutationWrapper, true);
d.removeEventListener('DOMNodeInserted', mutationWrapper, true);
d.removeEventListener('DOMNodeRemoved', mutationWrapper, true);
d.isCaching = false;
}
},
// enable/disable context caching system
// @d optional document context (iframe, xml document)
// script loading context will be used as default context
setCache =
function(enable, d) {
if (!!enable) {
isExpired = false;
startMutation(d);
} else {
isExpired = true;
stopMutation(d);
}
isEnabled = !!enable;
},
// expire complete cache
// can be invoked by Mutation Events or
// programmatically by other code/scripts
// document context is mandatory no checks
expireCache =
function(d) {
isExpired = true;
Contexts = { };
Results = { };
};
if (!NATIVE_MUTATION_EVENTS && root.addEventListener && Element && Element.prototype) {
if (mutationTest('DOMNodeInserted', function(e) { e.appendChild(document.createElement('div')); }) &&
mutationTest('DOMNodeRemoved', function(e) { e.removeChild(e.appendChild(document.createElement('div'))); })) {
HACKED_MUTATION_EVENTS = true;
Element.prototype._setAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute =
function(name, val) {
this._setAttribute(name, val);
mutationWrapper({
target: this,
type: 'DOMAttrModified',
attrName: name,
attrValue: val });
};
}
}
isEnabled = NATIVE_MUTATION_EVENTS || HACKED_MUTATION_EVENTS;
/*------------------------------- PUBLIC API -------------------------------*/
// save results into cache
Dom.saveResults = saveResults;
// load results from cache
Dom.loadResults = loadResults;
// expire DOM tree cache
Dom.expireCache = expireCache;
// enable/disable cache
Dom.setCache = setCache;
})(this);
``` | /content/code_sandbox/node_modules/nwmatcher/src/modules/nwmatcher-cache.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,198 |
```javascript
NW.Dom.shortcuts = (function() {
// match missing R/L context
var nextID = 0,
reLeftContext = /^[\x20\t\n\r\f]*[>+~]/,
reRightContext = /[>+~][\x20\t\n\r\f]*$/;
return function(selector, from, alt) {
// add left context if missing
if (reLeftContext.test(selector)) {
if (from.nodeType == 9) {
selector = '* ' + selector;
} else if (/html|body/i.test(from.nodeName)) {
selector = from.nodeName + ' ' + selector;
} else if (alt) {
selector = NW.Dom.shortcuts(selector, alt);
} else if (from.nodeType == 1 && from.id) {
selector = '#' + from.id + ' ' + selector;
} else {
++nextID;
selector = '#' + (from.id = 'NW' + nextID) + ' ' + selector;
//NW.Dom.emit('Unable to resolve a context for the shortcut selector "' + selector + '"');
}
}
// add right context if missing
if (reRightContext.test(selector)) {
selector += ' *';
}
return selector;
};
})();
``` | /content/code_sandbox/node_modules/nwmatcher/src/modules/nwmatcher-shortcuts.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 269 |
```javascript
/*
* All rights reserved.
*
* CSS3 pseudo-classes extension for NWMatcher
*
* Added capabilities:
*
* - structural pseudo-classes
*
* :root, :empty,
* :nth-child(), nth-of-type(),
* :nth-last-child(), nth-last-of-type(),
* :first-child, :last-child, :only-child
* :first-of-type, :last-of-type, :only-of-type
*
* - negation, language, target and UI element pseudo-classes
*
* :not(), :target, :lang(), :target
* :link, :visited, :active, :focus, :hover,
* :checked, :disabled, :enabled, :selected
*/
(function(global) {
var LINK_NODES = {
'a': 1, 'A': 1,
'area': 1, 'AREA': 1,
'link': 1, 'LINK': 1
},
root = document.documentElement,
contains = 'compareDocumentPosition' in root ?
function(container, element) {
return (container.compareDocumentPosition(element) & 16) == 16;
} : 'contains' in root ?
function(container, element) {
return element.nodeType == 1 && container.contains(element);
} :
function(container, element) {
while ((element = element.parentNode) && element.nodeType == 1) {
if (element === container) return true;
}
return false;
},
isLink =
function(element) {
return element.getAttribute('href') && LINK_NODES[element.nodeName];
},
isEmpty =
function(node) {
node = node.firstChild;
while (node) {
if (node.nodeType == 3 || node.nodeName > '@') return false;
node = node.nextSibling;
}
return true;
},
nthElement =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling';
while ((element = element[succ])) {
if (element.nodeName > '@') ++count;
}
return count;
},
nthOfType =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling', type = element.nodeName;
while ((element = element[succ])) {
if (element.nodeName == type) ++count;
}
return count;
};
NW.Dom.Snapshot['contains'] = contains;
NW.Dom.Snapshot['isLink'] = isLink;
NW.Dom.Snapshot['isEmpty'] = isEmpty;
NW.Dom.Snapshot['nthOfType'] = nthOfType;
NW.Dom.Snapshot['nthElement'] = nthElement;
})(this);
NW.Dom.registerSelector(
'nwmatcher:spseudos',
/^\:(root|empty|(?:first|last|only)(?:-child|-of-type)|nth(?:-last)?(?:-child|-of-type)\(\s*(even|odd|(?:[-+]{0,1}\d*n\s*)?[-+]{0,1}\s*\d*)\s*\))?(.*)/i,
(function(global) {
return function(match, source) {
var a, n, b, status = true, test, type;
switch (match[1]) {
case 'root':
if (match[3])
source = 'if(e===h||s.contains(h,e)){' + source + '}';
else
source = 'if(e===h){' + source + '}';
break;
case 'empty':
source = 'if(s.isEmpty(e)){' + source + '}';
break;
default:
if (match[1] && match[2]) {
if (match[2] == 'n') {
source = 'if(e!==h){' + source + '}';
break;
} else if (match[2] == 'even') {
a = 2;
b = 0;
} else if (match[2] == 'odd') {
a = 2;
b = 1;
} else {
b = ((n = match[2].match(/(-?\d+)$/)) ? parseInt(n[1], 10) : 0);
a = ((n = match[2].match(/(-?\d*)n/i)) ? parseInt(n[1], 10) : 0);
if (n && n[1] == '-') a = -1;
}
test = a > 1 ?
(/last/i.test(match[1])) ? '(n-(' + b + '))%' + a + '==0' :
'n>=' + b + '&&(n-(' + b + '))%' + a + '==0' : a < -1 ?
(/last/i.test(match[1])) ? '(n-(' + b + '))%' + a + '==0' :
'n<=' + b + '&&(n-(' + b + '))%' + a + '==0' : a === 0 ?
'n==' + b : a == -1 ? 'n<=' + b : 'n>=' + b;
source =
'if(e!==h){' +
'n=s[' + (/-of-type/i.test(match[1]) ? '"nthOfType"' : '"nthElement"') + ']' +
'(e,' + (/last/i.test(match[1]) ? 'true' : 'false') + ');' +
'if(' + test + '){' + source + '}' +
'}';
} else if (match[1]) {
a = /first/i.test(match[1]) ? 'previous' : 'next';
n = /only/i.test(match[1]) ? 'previous' : 'next';
b = /first|last/i.test(match[1]);
type = /-of-type/i.test(match[1]) ? '&&n.nodeName!==e.nodeName' : '&&n.nodeName<"@"';
source = 'if(e!==h){' +
( 'n=e;while((n=n.' + a + 'Sibling)' + type + ');if(!n){' + (b ? source :
'n=e;while((n=n.' + n + 'Sibling)' + type + ');if(!n){' + source + '}') + '}' ) + '}';
} else {
status = false;
}
break;
}
return {
'source': source,
'status': status
};
};
})(this));
NW.Dom.registerSelector(
'nwmatcher:dpseudos',
/^\:(link|visited|target|active|focus|hover|checked|disabled|enabled|selected|lang\(([-\w]{2,})\)|not\(\s*(:nth(?:-last)?(?:-child|-of-type)\(\s*(?:even|odd|(?:[-+]{0,1}\d*n\s*)?[-+]{0,1}\s*\d*)\s*\)|[^()]*)\s*\))?(.*)/i,
(function(global) {
var doc = global.document,
Config = NW.Dom.Config,
Tokens = NW.Dom.Tokens,
reTrimSpace = RegExp('^\\s+|\\s+$', 'g'),
reSimpleNot = RegExp('^((?!:not)' +
'(' + Tokens.prefixes + '|' + Tokens.identifier +
'|\\([^()]*\\))+|\\[' + Tokens.attributes + '\\])$');
return function(match, source) {
var expr, status = true, test;
switch (match[1].match(/^\w+/)[0]) {
case 'not':
expr = match[3].replace(reTrimSpace, '');
if (Config.SIMPLENOT && !reSimpleNot.test(expr)) {
NW.Dom.emit('Negation pseudo-class only accepts simple selectors "' + selector + '"');
} else {
if ('compatMode' in doc) {
source = 'if(!' + NW.Dom.compile(expr, '', false) + '(e,s,d,h,g)){' + source + '}';
} else {
source = 'if(!s.match(e, "' + expr.replace(/\x22/g, '\\"') + '",g)){' + source +'}';
}
}
break;
case 'checked':
source = 'if((typeof e.form!=="undefined"&&(/^(?:radio|checkbox)$/i).test(e.type)&&e.checked)' +
(Config.USE_HTML5 ? '||(/^option$/i.test(e.nodeName)&&(e.selected||e.checked))' : '') +
'){' + source + '}';
break;
case 'disabled':
source = 'if(((typeof e.form!=="undefined"' +
(Config.USE_HTML5 ? '' : '&&!(/^hidden$/i).test(e.type)') +
')||s.isLink(e))&&e.disabled===true){' + source + '}';
break;
case 'enabled':
source = 'if(((typeof e.form!=="undefined"' +
(Config.USE_HTML5 ? '' : '&&!(/^hidden$/i).test(e.type)') +
')||s.isLink(e))&&e.disabled===false){' + source + '}';
break;
case 'lang':
test = '';
if (match[2]) test = match[2].substr(0, 2) + '-';
source = 'do{(n=e.lang||"").toLowerCase();' +
'if((n==""&&h.lang=="' + match[2].toLowerCase() + '")||' +
'(n&&(n=="' + match[2].toLowerCase() +
'"||n.substr(0,3)=="' + test.toLowerCase() + '")))' +
'{' + source + 'break;}}while((e=e.parentNode)&&e!==g);';
break;
case 'target':
source = 'if(e.id==d.location.hash.slice(1)){' + source + '}';
break;
case 'link':
source = 'if(s.isLink(e)&&!e.visited){' + source + '}';
break;
case 'visited':
source = 'if(s.isLink(e)&&e.visited){' + source + '}';
break;
case 'active':
source = 'if(e===d.activeElement){' + source + '}';
break;
case 'hover':
source = 'if(e===d.hoverElement){' + source + '}';
break;
case 'focus':
source = 'hasFocus' in doc ?
'if(e===d.activeElement&&d.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number")){' + source + '}' :
'if(e===d.activeElement&&(e.type||e.href)){' + source + '}';
break;
case 'selected':
source = 'if(/^option$/i.test(e.nodeName)&&(e.selected||e.checked)){' + source + '}';
break;
default:
status = false;
break;
}
return {
'source': source,
'status': status
};
};
})(this));
NW.Dom.registerSelector(
'nwmatcher:epseudos',
/^((?:[:]{1,2}(?:after|before|first-letter|first-line))|(?:[:]{2,2}(?:selection|backdrop|placeholder)))?(.*)/i,
(function(global) {
return function(match, source) {
var status = true;
switch (match[1].match(/(\w+)$/)[0]) {
case 'after':
case 'before':
case 'first-letter':
case 'first-line':
case 'selection':
case 'backdrop':
case 'placeholder':
source = 'if(!(/1|11/).test(e.nodeType)){' + source + '}';
break;
default:
status = false;
break;
}
return {
'source': source,
'status': status
};
};
})(this));
``` | /content/code_sandbox/node_modules/nwmatcher/src/modules/nwmatcher-pseudos.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,583 |
```javascript
/*
* Element Traversal methods from Juriy Zaytsev (kangax)
* used to emulate Prototype up/down/previous/next methods
*/
(function(D){
// TODO: all of this needs tests
var match = D.match, select = D.select, root = document.documentElement,
// Use the Element Traversal API if available.
nextElement = 'nextElementSibling',
previousElement = 'previousElementSibling',
parentElement = 'parentElement';
// Fall back to the DOM Level 1 API.
if (!(nextElement in root)) nextElement = 'nextSibling';
if (!(previousElement in root)) previousElement = 'previousSibling';
if (!(parentElement in root)) parentElement = 'parentNode';
function walkElements(property, element, expr) {
var i = 0, isIndex = typeof expr == 'number';
if (typeof expr == 'undefined') {
isIndex = true;
expr = 0;
}
while ((element = element[property])) {
if (element.nodeType != 1) continue;
if (isIndex) {
++i;
if (i == expr) return element;
} else if (match(element, expr)) {
return element;
}
}
return null;
}
/**
* @method up
* @param {HTMLElement} element element to walk from
* @param {String | Number} expr CSS expression or an index
* @return {HTMLElement | null}
*/
function up(element, expr) {
return walkElements(parentElement, element, expr);
}
/**
* @method next
* @param {HTMLElement} element element to walk from
* @param {String | Number} expr CSS expression or an index
* @return {HTMLElement | null}
*/
function next(element, expr) {
return walkElements(nextElement, element, expr);
}
/**
* @method previous
* @param {HTMLElement} element element to walk from
* @param {String | Number} expr CSS expression or an index
* @return {HTMLElement | null}
*/
function previous(element, expr) {
return walkElements(previousElement, element, expr);
}
/**
* @method down
* @param {HTMLElement} element element to walk from
* @param {String | Number} expr CSS expression or an index
* @return {HTMLElement | null}
*/
function down(element, expr) {
var isIndex = typeof expr == 'number', descendants, index, descendant;
if (expr === null) {
element = element.firstChild;
while (element && element.nodeType != 1) element = element[nextElement];
return element;
}
if (!isIndex && match(element, expr) || isIndex && expr === 0) return element;
descendants = select('*', element);
if (isIndex) return descendants[expr] || null;
index = 0;
while ((descendant = descendants[index]) && !match(descendant, expr)) { ++index; }
return descendant || null;
}
D.up = up;
D.down = down;
D.next = next;
D.previous = previous;
})(NW.Dom);
``` | /content/code_sandbox/node_modules/nwmatcher/src/modules/nwmatcher-traversal.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 700 |
```javascript
/* eslint no-console: "off" */
var asynckit = require('./')
, async = require('async')
, assert = require('assert')
, expected = 0
;
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var source = [];
for (var z = 1; z < 100; z++)
{
source.push(z);
expected += z;
}
suite
// add tests
.add('async.map', function(deferred)
{
var total = 0;
async.map(source,
function(i, cb)
{
setImmediate(function()
{
total += i;
cb(null, total);
});
},
function(err, result)
{
assert.ifError(err);
assert.equal(result[result.length - 1], expected);
deferred.resolve();
});
}, {'defer': true})
.add('asynckit.parallel', function(deferred)
{
var total = 0;
asynckit.parallel(source,
function(i, cb)
{
setImmediate(function()
{
total += i;
cb(null, total);
});
},
function(err, result)
{
assert.ifError(err);
assert.equal(result[result.length - 1], expected);
deferred.resolve();
});
}, {'defer': true})
// add listeners
.on('cycle', function(ev)
{
console.log(String(ev.target));
})
.on('complete', function()
{
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
``` | /content/code_sandbox/node_modules/asynckit/bench.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 344 |
```javascript
module.exports =
{
parallel : require('./parallel.js'),
serial : require('./serial.js'),
serialOrdered : require('./serialOrdered.js')
};
``` | /content/code_sandbox/node_modules/asynckit/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 34 |
```javascript
var iterate = require('./lib/iterate.js')
, initState = require('./lib/state.js')
, terminator = require('./lib/terminator.js')
;
// Public API
module.exports = parallel;
/**
* Runs iterator over provided array elements in parallel
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function parallel(list, iterator, callback)
{
var state = initState(list);
while (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, function(error, result)
{
if (error)
{
callback(error, result);
return;
}
// looks like it's the last one
if (Object.keys(state.jobs).length === 0)
{
callback(null, state.results);
return;
}
});
state.index++;
}
return terminator.bind(state, callback);
}
``` | /content/code_sandbox/node_modules/asynckit/parallel.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 241 |
```javascript
var serialOrdered = require('./serialOrdered.js');
// Public API
module.exports = serial;
/**
* Runs iterator over provided array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serial(list, iterator, callback)
{
return serialOrdered(list, iterator, null, callback);
}
``` | /content/code_sandbox/node_modules/asynckit/serial.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 115 |
```javascript
var inherits = require('util').inherits
, Readable = require('stream').Readable
, ReadableAsyncKit = require('./lib/readable_asynckit.js')
, ReadableParallel = require('./lib/readable_parallel.js')
, ReadableSerial = require('./lib/readable_serial.js')
, ReadableSerialOrdered = require('./lib/readable_serial_ordered.js')
;
// API
module.exports =
{
parallel : ReadableParallel,
serial : ReadableSerial,
serialOrdered : ReadableSerialOrdered,
};
inherits(ReadableAsyncKit, Readable);
inherits(ReadableParallel, ReadableAsyncKit);
inherits(ReadableSerial, ReadableAsyncKit);
inherits(ReadableSerialOrdered, ReadableAsyncKit);
``` | /content/code_sandbox/node_modules/asynckit/stream.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 164 |
```javascript
var iterate = require('./lib/iterate.js')
, initState = require('./lib/state.js')
, terminator = require('./lib/terminator.js')
;
// Public API
module.exports = serialOrdered;
// sorting helpers
module.exports.ascending = ascending;
module.exports.descending = descending;
/**
* Runs iterator over provided sorted array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} sortMethod - custom sort function
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serialOrdered(list, iterator, sortMethod, callback)
{
var state = initState(list, sortMethod);
iterate(list, iterator, state, function iteratorHandler(error, result)
{
if (error)
{
callback(error, result);
return;
}
state.index++;
// are we there yet?
if (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, iteratorHandler);
return;
}
// done here
callback(null, state.results);
});
return terminator.bind(state, callback);
}
/*
* -- Sort methods
*/
/**
* sort helper to sort array elements in ascending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function ascending(a, b)
{
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* sort helper to sort array elements in descending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function descending(a, b)
{
return -1 * ascending(a, b);
}
``` | /content/code_sandbox/node_modules/asynckit/serialOrdered.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 437 |
```javascript
// API
module.exports = abort;
/**
* Aborts leftover active jobs
*
* @param {object} state - current state object
*/
function abort(state)
{
Object.keys(state.jobs).forEach(clean.bind(state));
// reset leftover jobs
state.jobs = {};
}
/**
* Cleans up leftover job by invoking abort function for the provided job id
*
* @this state
* @param {string|number} key - job id to abort
*/
function clean(key)
{
if (typeof this.jobs[key] == 'function')
{
this.jobs[key]();
}
}
``` | /content/code_sandbox/node_modules/asynckit/lib/abort.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 126 |
```javascript
var defer = require('./defer.js');
// API
module.exports = async;
/**
* Runs provided callback asynchronously
* even if callback itself is not
*
* @param {function} callback - callback to invoke
* @returns {function} - augmented callback
*/
function async(callback)
{
var isAsync = false;
// check if async happened
defer(function() { isAsync = true; });
return function async_callback(err, result)
{
if (isAsync)
{
callback(err, result);
}
else
{
defer(function nextTick_callback()
{
callback(err, result);
});
}
};
}
``` | /content/code_sandbox/node_modules/asynckit/lib/async.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 141 |
```javascript
var parallel = require('../parallel.js');
// API
module.exports = ReadableParallel;
/**
* Streaming wrapper to `asynckit.parallel`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableParallel(list, iterator, callback)
{
if (!(this instanceof ReadableParallel))
{
return new ReadableParallel(list, iterator, callback);
}
// turn on object mode
ReadableParallel.super_.call(this, {objectMode: true});
this._start(parallel, list, iterator, callback);
}
``` | /content/code_sandbox/node_modules/asynckit/lib/readable_parallel.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 164 |
```javascript
// API
module.exports = state;
/**
* Creates initial state object
* for iteration over list
*
* @param {array|object} list - list to iterate over
* @param {function|null} sortMethod - function to use for keys sort,
* or `null` to keep them as is
* @returns {object} - initial state object
*/
function state(list, sortMethod)
{
var isNamedList = !Array.isArray(list)
, initState =
{
index : 0,
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
jobs : {},
results : isNamedList ? {} : [],
size : isNamedList ? Object.keys(list).length : list.length
}
;
if (sortMethod)
{
// sort array keys based on it's values
// sort object's keys just on own merit
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
{
return sortMethod(list[a], list[b]);
});
}
return initState;
}
``` | /content/code_sandbox/node_modules/asynckit/lib/state.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 236 |
```javascript
var streamify = require('./streamify.js')
, defer = require('./defer.js')
;
// API
module.exports = ReadableAsyncKit;
/**
* Base constructor for all streams
* used to hold properties/methods
*/
function ReadableAsyncKit()
{
ReadableAsyncKit.super_.apply(this, arguments);
// list of active jobs
this.jobs = {};
// add stream methods
this.destroy = destroy;
this._start = _start;
this._read = _read;
}
/**
* Destroys readable stream,
* by aborting outstanding jobs
*
* @returns {void}
*/
function destroy()
{
if (this.destroyed)
{
return;
}
this.destroyed = true;
if (typeof this.terminator == 'function')
{
this.terminator();
}
}
/**
* Starts provided jobs in async manner
*
* @private
*/
function _start()
{
// first argument runner function
var runner = arguments[0]
// take away first argument
, args = Array.prototype.slice.call(arguments, 1)
// second argument - input data
, input = args[0]
// last argument - result callback
, endCb = streamify.callback.call(this, args[args.length - 1])
;
args[args.length - 1] = endCb;
// third argument - iterator
args[1] = streamify.iterator.call(this, args[1]);
// allow time for proper setup
defer(function()
{
if (!this.destroyed)
{
this.terminator = runner.apply(null, args);
}
else
{
endCb(null, Array.isArray(input) ? [] : {});
}
}.bind(this));
}
/**
* Implement _read to comply with Readable streams
* Doesn't really make sense for flowing object mode
*
* @private
*/
function _read()
{
}
``` | /content/code_sandbox/node_modules/asynckit/lib/readable_asynckit.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 419 |
```javascript
module.exports = defer;
/**
* Runs provided function on next iteration of the event loop
*
* @param {function} fn - function to run
*/
function defer(fn)
{
var nextTick = typeof setImmediate == 'function'
? setImmediate
: (
typeof process == 'object' && typeof process.nextTick == 'function'
? process.nextTick
: null
);
if (nextTick)
{
nextTick(fn);
}
else
{
setTimeout(fn, 0);
}
}
``` | /content/code_sandbox/node_modules/asynckit/lib/defer.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 116 |
```javascript
var serialOrdered = require('../serialOrdered.js');
// API
module.exports = ReadableSerialOrdered;
// expose sort helpers
module.exports.ascending = serialOrdered.ascending;
module.exports.descending = serialOrdered.descending;
/**
* Streaming wrapper to `asynckit.serialOrdered`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} sortMethod - custom sort function
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableSerialOrdered(list, iterator, sortMethod, callback)
{
if (!(this instanceof ReadableSerialOrdered))
{
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
}
// turn on object mode
ReadableSerialOrdered.super_.call(this, {objectMode: true});
this._start(serialOrdered, list, iterator, sortMethod, callback);
}
``` | /content/code_sandbox/node_modules/asynckit/lib/readable_serial_ordered.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 221 |
```javascript
var serial = require('../serial.js');
// API
module.exports = ReadableSerial;
/**
* Streaming wrapper to `asynckit.serial`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableSerial(list, iterator, callback)
{
if (!(this instanceof ReadableSerial))
{
return new ReadableSerial(list, iterator, callback);
}
// turn on object mode
ReadableSerial.super_.call(this, {objectMode: true});
this._start(serial, list, iterator, callback);
}
``` | /content/code_sandbox/node_modules/asynckit/lib/readable_serial.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 163 |
```javascript
var async = require('./async.js');
// API
module.exports = {
iterator: wrapIterator,
callback: wrapCallback
};
/**
* Wraps iterators with long signature
*
* @this ReadableAsyncKit#
* @param {function} iterator - function to wrap
* @returns {function} - wrapped function
*/
function wrapIterator(iterator)
{
var stream = this;
return function(item, key, cb)
{
var aborter
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
;
stream.jobs[key] = wrappedCb;
// it's either shortcut (item, cb)
if (iterator.length == 2)
{
aborter = iterator(item, wrappedCb);
}
// or long format (item, key, cb)
else
{
aborter = iterator(item, key, wrappedCb);
}
return aborter;
};
}
/**
* Wraps provided callback function
* allowing to execute snitch function before
* real callback
*
* @this ReadableAsyncKit#
* @param {function} callback - function to wrap
* @returns {function} - wrapped function
*/
function wrapCallback(callback)
{
var stream = this;
var wrapped = function(error, result)
{
return finisher.call(stream, error, result, callback);
};
return wrapped;
}
/**
* Wraps provided iterator callback function
* makes sure snitch only called once,
* but passes secondary calls to the original callback
*
* @this ReadableAsyncKit#
* @param {function} callback - callback to wrap
* @param {number|string} key - iteration key
* @returns {function} wrapped callback
*/
function wrapIteratorCallback(callback, key)
{
var stream = this;
return function(error, output)
{
// don't repeat yourself
if (!(key in stream.jobs))
{
callback(error, output);
return;
}
// clean up jobs
delete stream.jobs[key];
return streamer.call(stream, error, {key: key, value: output}, callback);
};
}
/**
* Stream wrapper for iterator callback
*
* @this ReadableAsyncKit#
* @param {mixed} error - error response
* @param {mixed} output - iterator output
* @param {function} callback - callback that expects iterator results
*/
function streamer(error, output, callback)
{
if (error && !this.error)
{
this.error = error;
this.pause();
this.emit('error', error);
// send back value only, as expected
callback(error, output && output.value);
return;
}
// stream stuff
this.push(output);
// back to original track
// send back value only, as expected
callback(error, output && output.value);
}
/**
* Stream wrapper for finishing callback
*
* @this ReadableAsyncKit#
* @param {mixed} error - error response
* @param {mixed} output - iterator output
* @param {function} callback - callback that expects final results
*/
function finisher(error, output, callback)
{
// signal end of the stream
// only for successfully finished streams
if (!error)
{
this.push(null);
}
// back to original track
callback(error, output);
}
``` | /content/code_sandbox/node_modules/asynckit/lib/streamify.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 724 |
```javascript
var abort = require('./abort.js')
, async = require('./async.js')
;
// API
module.exports = terminator;
/**
* Terminates jobs in the attached state context
*
* @this AsyncKitState#
* @param {function} callback - final callback to invoke after termination
*/
function terminator(callback)
{
if (!Object.keys(this.jobs).length)
{
return;
}
// fast forward iteration index
this.index = this.size;
// abort jobs
abort(this);
// send back results we have so far
async(callback)(null, this.results);
}
``` | /content/code_sandbox/node_modules/asynckit/lib/terminator.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 129 |
```javascript
var async = require('./async.js')
, abort = require('./abort.js')
;
// API
module.exports = iterate;
/**
* Iterates over each job object
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {object} state - current job status
* @param {function} callback - invoked when all elements processed
*/
function iterate(list, iterator, state, callback)
{
// store current index
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
{
// don't repeat yourself
// skip secondary callbacks
if (!(key in state.jobs))
{
return;
}
// clean up jobs
delete state.jobs[key];
if (error)
{
// don't process rest of the results
// stop still active jobs
// and reset the list
abort(state);
}
else
{
state.results[key] = output;
}
// return salvaged results
callback(error, state.results);
});
}
/**
* Runs iterator over provided job element
*
* @param {function} iterator - iterator to invoke
* @param {string|number} key - key/index of the element in the list of jobs
* @param {mixed} item - job description
* @param {function} callback - invoked after iterator is done with the job
* @returns {function|mixed} - job abort function or something else
*/
function runJob(iterator, key, item, callback)
{
var aborter;
// allow shortcut if iterator expects only two arguments
if (iterator.length == 2)
{
aborter = iterator(item, async(callback));
}
// otherwise go with full three arguments
else
{
aborter = iterator(item, key, async(callback));
}
return aborter;
}
``` | /content/code_sandbox/node_modules/asynckit/lib/iterate.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 445 |
```javascript
// Generated by LiveScript 1.2.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
function consumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
} else {
throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
}
}
function maybeConsumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
}
}
function consumeList(tokens, delimiters, hasDelimiters){
var result;
if (hasDelimiters) {
consumeOp(tokens, delimiters[0]);
}
result = [];
while (tokens.length && tokens[0] !== delimiters[1]) {
result.push(consumeElement(tokens));
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, delimiters[1]);
}
return result;
}
function consumeArray(tokens, hasDelimiters){
return consumeList(tokens, ['[', ']'], hasDelimiters);
}
function consumeTuple(tokens, hasDelimiters){
return consumeList(tokens, ['(', ')'], hasDelimiters);
}
function consumeFields(tokens, hasDelimiters){
var result, key;
if (hasDelimiters) {
consumeOp(tokens, '{');
}
result = {};
while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
key = tokens.shift();
consumeOp(tokens, ':');
result[key] = consumeElement(tokens);
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, '}');
}
return result;
}
function consumeElement(tokens){
switch (tokens[0]) {
case '[':
return consumeArray(tokens, true);
case '(':
return consumeTuple(tokens, true);
case '{':
return consumeFields(tokens, true);
default:
return tokens.shift();
}
}
function consumeTopLevel(tokens, types){
var ref$, type, structure, origTokens, result, finalResult, x$, y$;
ref$ = types[0], type = ref$.type, structure = ref$.structure;
origTokens = tokens.concat();
if (types.length === 1 && (structure || (type === 'Array' || type === 'Object'))) {
result = structure === 'array' || type === 'Array'
? consumeArray(tokens, tokens[0] === '[')
: structure === 'tuple'
? consumeTuple(tokens, tokens[0] === '(')
: consumeFields(tokens, tokens[0] === '{');
finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array'
? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$)
: (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
} else {
finalResult = consumeElement(tokens);
}
if (tokens.length && origTokens.length) {
throw new Error("Unable to parse " + JSON.stringify(origTokens) + " of type " + JSON.stringify(types) + ".");
} else {
return finalResult;
}
}
special = /\[\]\(\)}{:,/.source;
tokenRegex = RegExp('("(?:[^"]|\\\\")*")|(\'(?:[^\']|\\\\\')*\')|(#.*#)|(/(?:\\\\/|[^/])*/[gimy]*)|([' + special + '])|([^\\s' + special + ']+)|\\s*');
module.exports = function(string, types){
var tokens, node;
tokens = reject(function(it){
return !it || /^\s+$/.test(it);
}, string.split(tokenRegex));
node = consumeTopLevel(tokens, types);
if (!node) {
throw new Error("Error parsing '" + string + "'.");
}
return node;
};
}).call(this);
``` | /content/code_sandbox/node_modules/levn/lib/parse.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 900 |
```javascript
// Generated by LiveScript 1.4.0
(function(){
var parseString, cast, parseType, VERSION, parsedTypeParse, parse;
parseString = require('./parse-string');
cast = require('./cast');
parseType = require('type-check').parseType;
VERSION = '0.3.0';
parsedTypeParse = function(parsedType, string, options){
options == null && (options = {});
options.explicit == null && (options.explicit = false);
options.customTypes == null && (options.customTypes = {});
return cast(parseString(parsedType, string, options), parsedType, options);
};
parse = function(type, string, options){
return parsedTypeParse(parseType(type), string, options);
};
module.exports = {
VERSION: VERSION,
parse: parse,
parsedTypeParse: parsedTypeParse
};
}).call(this);
``` | /content/code_sandbox/node_modules/levn/lib/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 194 |
```javascript
// Generated by LiveScript 1.4.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
function consumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
} else {
throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
}
}
function maybeConsumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
}
}
function consumeList(tokens, arg$, hasDelimiters){
var open, close, result, untilTest;
open = arg$[0], close = arg$[1];
if (hasDelimiters) {
consumeOp(tokens, open);
}
result = [];
untilTest = "," + (hasDelimiters ? close : '');
while (tokens.length && (hasDelimiters && tokens[0] !== close)) {
result.push(consumeElement(tokens, untilTest));
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, close);
}
return result;
}
function consumeArray(tokens, hasDelimiters){
return consumeList(tokens, ['[', ']'], hasDelimiters);
}
function consumeTuple(tokens, hasDelimiters){
return consumeList(tokens, ['(', ')'], hasDelimiters);
}
function consumeFields(tokens, hasDelimiters){
var result, untilTest, key;
if (hasDelimiters) {
consumeOp(tokens, '{');
}
result = {};
untilTest = "," + (hasDelimiters ? '}' : '');
while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
key = consumeValue(tokens, ':');
consumeOp(tokens, ':');
result[key] = consumeElement(tokens, untilTest);
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, '}');
}
return result;
}
function consumeValue(tokens, untilTest){
var out;
untilTest == null && (untilTest = '');
out = '';
while (tokens.length && -1 === untilTest.indexOf(tokens[0])) {
out += tokens.shift();
}
return out;
}
function consumeElement(tokens, untilTest){
switch (tokens[0]) {
case '[':
return consumeArray(tokens, true);
case '(':
return consumeTuple(tokens, true);
case '{':
return consumeFields(tokens, true);
default:
return consumeValue(tokens, untilTest);
}
}
function consumeTopLevel(tokens, types, options){
var ref$, type, structure, origTokens, result, finalResult, x$, y$;
ref$ = types[0], type = ref$.type, structure = ref$.structure;
origTokens = tokens.concat();
if (!options.explicit && types.length === 1 && ((!type && structure) || (type === 'Array' || type === 'Object'))) {
result = structure === 'array' || type === 'Array'
? consumeArray(tokens, tokens[0] === '[')
: structure === 'tuple'
? consumeTuple(tokens, tokens[0] === '(')
: consumeFields(tokens, tokens[0] === '{');
finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array'
? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$)
: (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
} else {
finalResult = consumeElement(tokens);
}
return finalResult;
}
special = /\[\]\(\)}{:,/.source;
tokenRegex = RegExp('("(?:\\\\"|[^"])*")|(\'(?:\\\\\'|[^\'])*\')|(/(?:\\\\/|[^/])*/[a-zA-Z]*)|(#.*#)|([' + special + '])|([^\\s' + special + '](?:\\s*[^\\s' + special + ']+)*)|\\s*');
module.exports = function(types, string, options){
var tokens, node;
options == null && (options = {});
if (!options.explicit && types.length === 1 && types[0].type === 'String') {
return "'" + string.replace(/\\'/g, "\\\\'") + "'";
}
tokens = reject(not$, string.split(tokenRegex));
node = consumeTopLevel(tokens, types, options);
if (!node) {
throw new Error("Error parsing '" + string + "'.");
}
return node;
};
function not$(x){ return !x; }
}).call(this);
``` | /content/code_sandbox/node_modules/levn/lib/parse-string.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,054 |
```javascript
// Generated by LiveScript 1.4.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
types = {
'*': function(value, options){
switch (toString$.call(value).slice(8, -1)) {
case 'Array':
return typeCast(value, {
type: 'Array'
}, options);
case 'Object':
return typeCast(value, {
type: 'Object'
}, options);
default:
return {
type: 'Just',
value: typesCast(value, [
{
type: 'Undefined'
}, {
type: 'Null'
}, {
type: 'NaN'
}, {
type: 'Boolean'
}, {
type: 'Number'
}, {
type: 'Date'
}, {
type: 'RegExp'
}, {
type: 'Array'
}, {
type: 'Object'
}, {
type: 'String'
}
], (options.explicit = true, options))
};
}
},
Undefined: function(it){
if (it === 'undefined' || it === void 8) {
return {
type: 'Just',
value: void 8
};
} else {
return {
type: 'Nothing'
};
}
},
Null: function(it){
if (it === 'null') {
return {
type: 'Just',
value: null
};
} else {
return {
type: 'Nothing'
};
}
},
NaN: function(it){
if (it === 'NaN') {
return {
type: 'Just',
value: NaN
};
} else {
return {
type: 'Nothing'
};
}
},
Boolean: function(it){
if (it === 'true') {
return {
type: 'Just',
value: true
};
} else if (it === 'false') {
return {
type: 'Just',
value: false
};
} else {
return {
type: 'Nothing'
};
}
},
Number: function(it){
return {
type: 'Just',
value: +it
};
},
Int: function(it){
return {
type: 'Just',
value: +it
};
},
Float: function(it){
return {
type: 'Just',
value: +it
};
},
Date: function(value, options){
var that;
if (that = /^\#([\s\S]*)\#$/.exec(value)) {
return {
type: 'Just',
value: new Date(+that[1] || that[1])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new Date(+value || value)
};
}
},
RegExp: function(value, options){
var that;
if (that = /^\/([\s\S]*)\/([gimy]*)$/.exec(value)) {
return {
type: 'Just',
value: new RegExp(that[1], that[2])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new RegExp(value)
};
}
},
Array: function(value, options){
return castArray(value, {
of: [{
type: '*'
}]
}, options);
},
Object: function(value, options){
return castFields(value, {
of: {}
}, options);
},
String: function(it){
var that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
if (that = it.match(/^'([\s\S]*)'$/)) {
return {
type: 'Just',
value: that[1].replace(/\\'/g, "'")
};
} else if (that = it.match(/^"([\s\S]*)"$/)) {
return {
type: 'Just',
value: that[1].replace(/\\"/g, '"')
};
} else {
return {
type: 'Just',
value: it
};
}
}
};
function castArray(node, type, options){
var typeOf, element;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
element = ref$[i$];
results$.push(typesCast(element, typeOf, options));
}
return results$;
}())
};
}
function castTuple(node, type, options){
var result, i, i$, ref$, len$, types, cast;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
result = [];
i = 0;
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
types = ref$[i$];
cast = typesCast(node[i], types, options);
if (toString$.call(cast).slice(8, -1) !== 'Undefined') {
result.push(cast);
}
i++;
}
if (node.length <= i) {
return {
type: 'Just',
value: result
};
} else {
return {
type: 'Nothing'
};
}
}
function castFields(node, type, options){
var typeOf, key, value;
if (toString$.call(node).slice(8, -1) !== 'Object') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var ref$, resultObj$ = {};
for (key in ref$ = node) {
value = ref$[key];
resultObj$[typesCast(key, [{
type: 'String'
}], options)] = typesCast(value, typeOf[key] || [{
type: '*'
}], options);
}
return resultObj$;
}())
};
}
function typeCast(node, typeObj, options){
var type, structure, castFunc, ref$;
type = typeObj.type, structure = typeObj.structure;
if (type) {
castFunc = ((ref$ = options.customTypes[type]) != null ? ref$.cast : void 8) || types[type];
if (!castFunc) {
throw new Error("Type not defined: " + type + ".");
}
return castFunc(node, options, typesCast);
} else {
switch (structure) {
case 'array':
return castArray(node, typeObj, options);
case 'tuple':
return castTuple(node, typeObj, options);
case 'fields':
return castFields(node, typeObj, options);
}
}
}
function typesCast(node, types, options){
var i$, len$, type, ref$, valueType, value;
for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
type = types[i$];
ref$ = typeCast(node, type, options), valueType = ref$.type, value = ref$.value;
if (valueType === 'Nothing') {
continue;
}
if (parsedTypeCheck([type], value, {
customTypes: options.customTypes
})) {
return value;
}
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = typesCast;
}).call(this);
``` | /content/code_sandbox/node_modules/levn/lib/cast.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,825 |
```javascript
var fs = require("fs");
var zlib = require("zlib");
var fd_slicer = require("fd-slicer");
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var Transform = require("stream").Transform;
var PassThrough = require("stream").PassThrough;
var Writable = require("stream").Writable;
exports.open = open;
exports.fromFd = fromFd;
exports.fromBuffer = fromBuffer;
exports.fromRandomAccessReader = fromRandomAccessReader;
exports.dosDateTimeToDate = dosDateTimeToDate;
exports.ZipFile = ZipFile;
exports.Entry = Entry;
exports.RandomAccessReader = RandomAccessReader;
function open(path, options, callback) {
if (typeof options === "function") {
callback = options;
options = null;
}
if (options == null) options = {};
if (options.autoClose == null) options.autoClose = true;
if (options.lazyEntries == null) options.lazyEntries = false;
if (callback == null) callback = defaultCallback;
fs.open(path, "r", function(err, fd) {
if (err) return callback(err);
fromFd(fd, options, function(err, zipfile) {
if (err) fs.close(fd, defaultCallback);
callback(err, zipfile);
});
});
}
function fromFd(fd, options, callback) {
if (typeof options === "function") {
callback = options;
options = null;
}
if (options == null) options = {};
if (options.autoClose == null) options.autoClose = false;
if (options.lazyEntries == null) options.lazyEntries = false;
if (callback == null) callback = defaultCallback;
fs.fstat(fd, function(err, stats) {
if (err) return callback(err);
var reader = fd_slicer.createFromFd(fd, {autoClose: true});
fromRandomAccessReader(reader, stats.size, options, callback);
});
}
function fromBuffer(buffer, options, callback) {
if (typeof options === "function") {
callback = options;
options = null;
}
if (options == null) options = {};
options.autoClose = false;
if (options.lazyEntries == null) options.lazyEntries = false;
// i got your open file right here.
var reader = fd_slicer.createFromBuffer(buffer);
fromRandomAccessReader(reader, buffer.length, options, callback);
}
function fromRandomAccessReader(reader, totalSize, options, callback) {
if (typeof options === "function") {
callback = options;
options = null;
}
if (options == null) options = {};
if (options.autoClose == null) options.autoClose = true;
if (options.lazyEntries == null) options.lazyEntries = false;
if (callback == null) callback = defaultCallback;
if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
if (totalSize > Number.MAX_SAFE_INTEGER) {
throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
}
// the matching unref() call is in zipfile.close()
reader.ref();
// eocdr means End of Central Directory Record.
// search backwards for the eocdr signature.
// the last field of the eocdr is a variable-length comment.
// the comment size is encoded in a 2-byte field in the eocdr, which we can't find without trudging backwards through the comment to find it.
// as a consequence of this design decision, it's possible to have ambiguous zip file metadata if a coherent eocdr was in the comment.
// we search backwards for a eocdr signature, and hope that whoever made the zip file was smart enough to forbid the eocdr signature in the comment.
var eocdrWithoutCommentSize = 22;
var maxCommentSize = 0x10000; // 2-byte size
var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize);
var buffer = new Buffer(bufferSize);
var bufferReadStart = totalSize - buffer.length;
readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
if (err) return callback(err);
for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
if (buffer.readUInt32LE(i) !== 0x06054b50) continue;
// found eocdr
var eocdrBuffer = buffer.slice(i);
// 0 - End of central directory signature = 0x06054b50
// 4 - Number of this disk
var diskNumber = eocdrBuffer.readUInt16LE(4);
if (diskNumber !== 0) return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
// 6 - Disk where central directory starts
// 8 - Number of central directory records on this disk
// 10 - Total number of central directory records
var entryCount = eocdrBuffer.readUInt16LE(10);
// 12 - Size of central directory (bytes)
// 16 - Offset of start of central directory, relative to start of archive
var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
// 20 - Comment length
var commentLength = eocdrBuffer.readUInt16LE(20);
var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
if (commentLength !== expectedCommentLength) {
return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength));
}
// 22 - Comment
// the encoding is always cp437.
var comment = bufferToString(eocdrBuffer, 22, eocdrBuffer.length, false);
if (!(entryCount === 0xffff || centralDirectoryOffset === 0xffffffff)) {
return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries));
}
// ZIP64 format
// ZIP64 Zip64 end of central directory locator
var zip64EocdlBuffer = new Buffer(20);
var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length;
readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err) {
if (err) return callback(err);
// 0 - zip64 end of central dir locator signature = 0x07064b50
if (zip64EocdlBuffer.readUInt32LE(0) !== 0x07064b50) {
return callback(new Error("invalid ZIP64 End of Central Directory Locator signature"));
}
// 4 - number of the disk with the start of the zip64 end of central directory
// 8 - relative offset of the zip64 end of central directory record
var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
// 16 - total number of disks
// ZIP64 end of central directory record
var zip64EocdrBuffer = new Buffer(56);
readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
if (err) return callback(err);
// 0 - zip64 end of central dir signature 4 bytes (0x06064b50)
if (zip64EocdrBuffer.readUInt32LE(0) !== 0x06064b50) return callback(new Error("invalid ZIP64 end of central directory record signature"));
// 4 - size of zip64 end of central directory record 8 bytes
// 12 - version made by 2 bytes
// 14 - version needed to extract 2 bytes
// 16 - number of this disk 4 bytes
// 20 - number of the disk with the start of the central directory 4 bytes
// 24 - total number of entries in the central directory on this disk 8 bytes
// 32 - total number of entries in the central directory 8 bytes
entryCount = readUInt64LE(zip64EocdrBuffer, 32);
// 40 - size of the central directory 8 bytes
// 48 - offset of start of central directory with respect to the starting disk number 8 bytes
centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
// 56 - zip64 extensible data sector (variable size)
return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries));
});
});
return;
}
callback(new Error("end of central directory record signature not found"));
});
}
util.inherits(ZipFile, EventEmitter);
function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries) {
var self = this;
EventEmitter.call(self);
self.reader = reader;
// forward close events
self.reader.on("error", function(err) {
// error closing the fd
emitError(self, err);
});
self.reader.once("close", function() {
self.emit("close");
});
self.readEntryCursor = centralDirectoryOffset;
self.fileSize = fileSize;
self.entryCount = entryCount;
self.comment = comment;
self.entriesRead = 0;
self.autoClose = !!autoClose;
self.lazyEntries = !!lazyEntries;
self.isOpen = true;
self.emittedError = false;
if (!self.lazyEntries) self.readEntry();
}
ZipFile.prototype.close = function() {
if (!this.isOpen) return;
this.isOpen = false;
this.reader.unref();
};
function emitErrorAndAutoClose(self, err) {
if (self.autoClose) self.close();
emitError(self, err);
}
function emitError(self, err) {
if (self.emittedError) return;
self.emittedError = true;
self.emit("error", err);
}
ZipFile.prototype.readEntry = function() {
var self = this;
if (self.entryCount === self.entriesRead) {
// done with metadata
setImmediate(function() {
if (self.autoClose) self.close();
if (self.emittedError) return;
self.emit("end");
});
return;
}
if (self.emittedError) return;
var buffer = new Buffer(46);
readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
if (err) return emitErrorAndAutoClose(self, err);
if (self.emittedError) return;
var entry = new Entry();
// 0 - Central directory file header signature
var signature = buffer.readUInt32LE(0);
if (signature !== 0x02014b50) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
// 4 - Version made by
entry.versionMadeBy = buffer.readUInt16LE(4);
// 6 - Version needed to extract (minimum)
entry.versionNeededToExtract = buffer.readUInt16LE(6);
// 8 - General purpose bit flag
entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
// 10 - Compression method
entry.compressionMethod = buffer.readUInt16LE(10);
// 12 - File last modification time
entry.lastModFileTime = buffer.readUInt16LE(12);
// 14 - File last modification date
entry.lastModFileDate = buffer.readUInt16LE(14);
// 16 - CRC-32
entry.crc32 = buffer.readUInt32LE(16);
// 20 - Compressed size
entry.compressedSize = buffer.readUInt32LE(20);
// 24 - Uncompressed size
entry.uncompressedSize = buffer.readUInt32LE(24);
// 28 - File name length (n)
entry.fileNameLength = buffer.readUInt16LE(28);
// 30 - Extra field length (m)
entry.extraFieldLength = buffer.readUInt16LE(30);
// 32 - File comment length (k)
entry.fileCommentLength = buffer.readUInt16LE(32);
// 34 - Disk number where file starts
// 36 - Internal file attributes
entry.internalFileAttributes = buffer.readUInt16LE(36);
// 38 - External file attributes
entry.externalFileAttributes = buffer.readUInt32LE(38);
// 42 - Relative offset of local file header
entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
self.readEntryCursor += 46;
buffer = new Buffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
if (err) return emitErrorAndAutoClose(self, err);
if (self.emittedError) return;
// 46 - File name
var isUtf8 = entry.generalPurposeBitFlag & 0x800
try {
entry.fileName = bufferToString(buffer, 0, entry.fileNameLength, isUtf8);
} catch (e) {
return emitErrorAndAutoClose(self, e);
}
// 46+n - Extra field
var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart);
entry.extraFields = [];
var i = 0;
while (i < extraFieldBuffer.length) {
var headerId = extraFieldBuffer.readUInt16LE(i + 0);
var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
var dataStart = i + 4;
var dataEnd = dataStart + dataSize;
var dataBuffer = new Buffer(dataSize);
extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd);
entry.extraFields.push({
id: headerId,
data: dataBuffer,
});
i = dataEnd;
}
// 46+n+m - File comment
try {
entry.fileComment = bufferToString(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8);
} catch (e) {
return emitErrorAndAutoClose(self, e);
}
self.readEntryCursor += buffer.length;
self.entriesRead += 1;
if (entry.uncompressedSize === 0xffffffff ||
entry.compressedSize === 0xffffffff ||
entry.relativeOffsetOfLocalHeader === 0xffffffff) {
// ZIP64 format
// find the Zip64 Extended Information Extra Field
var zip64EiefBuffer = null;
for (var i = 0; i < entry.extraFields.length; i++) {
var extraField = entry.extraFields[i];
if (extraField.id === 0x0001) {
zip64EiefBuffer = extraField.data;
break;
}
}
if (zip64EiefBuffer == null) return emitErrorAndAutoClose(self, new Error("expected Zip64 Extended Information Extra Field"));
var index = 0;
// 0 - Original Size 8 bytes
if (entry.uncompressedSize === 0xffffffff) {
if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, new Error("Zip64 Extended Information Extra Field does not include Original Size"));
entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
index += 8;
}
// 8 - Compressed Size 8 bytes
if (entry.compressedSize === 0xffffffff) {
if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, new Error("Zip64 Extended Information Extra Field does not include Compressed Size"));
entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
index += 8;
}
// 16 - Relative Header Offset 8 bytes
if (entry.relativeOffsetOfLocalHeader === 0xffffffff) {
if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, new Error("Zip64 Extended Information Extra Field does not include Relative Header Offset"));
entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
index += 8;
}
// 24 - Disk Start Number 4 bytes
}
// validate file size
if (entry.compressionMethod === 0) {
if (entry.compressedSize !== entry.uncompressedSize) {
var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
return emitErrorAndAutoClose(self, new Error(msg));
}
}
// validate file name
if (entry.fileName.indexOf("\\") !== -1) return emitErrorAndAutoClose(self, new Error("invalid characters in fileName: " + entry.fileName));
if (/^[a-zA-Z]:/.test(entry.fileName) || /^\//.test(entry.fileName)) return emitErrorAndAutoClose(self, new Error("absolute path: " + entry.fileName));
if (entry.fileName.split("/").indexOf("..") !== -1) return emitErrorAndAutoClose(self, new Error("invalid relative path: " + entry.fileName));
self.emit("entry", entry);
if (!self.lazyEntries) self.readEntry();
});
});
};
ZipFile.prototype.openReadStream = function(entry, callback) {
var self = this;
if (!self.isOpen) return callback(new Error("closed"));
// make sure we don't lose the fd before we open the actual read stream
self.reader.ref();
var buffer = new Buffer(30);
readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
try {
if (err) return callback(err);
// 0 - Local file header signature = 0x04034b50
var signature = buffer.readUInt32LE(0);
if (signature !== 0x04034b50) return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
// all this should be redundant
// 4 - Version needed to extract (minimum)
// 6 - General purpose bit flag
// 8 - Compression method
// 10 - File last modification time
// 12 - File last modification date
// 14 - CRC-32
// 18 - Compressed size
// 22 - Uncompressed size
// 26 - File name length (n)
var fileNameLength = buffer.readUInt16LE(26);
// 28 - Extra field length (m)
var extraFieldLength = buffer.readUInt16LE(28);
// 30 - File name
// 30+n - Extra field
var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength;
var compressed;
if (entry.compressionMethod === 0) {
// 0 - The file is stored (no compression)
compressed = false;
} else if (entry.compressionMethod === 8) {
// 8 - The file is Deflated
compressed = true;
} else {
return callback(new Error("unsupported compression method: " + entry.compressionMethod));
}
var fileDataStart = localFileHeaderEnd;
var fileDataEnd = fileDataStart + entry.compressedSize;
if (entry.compressedSize !== 0) {
// bounds check now, because the read streams will probably not complain loud enough.
// since we're dealing with an unsigned offset plus an unsigned size,
// we only have 1 thing to check for.
if (fileDataEnd > self.fileSize) {
return callback(new Error("file data overflows file bounds: " +
fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
}
}
var readStream = self.reader.createReadStream({start: fileDataStart, end: fileDataEnd});
var endpointStream = readStream;
if (compressed) {
var destroyed = false;
var inflateFilter = zlib.createInflateRaw();
readStream.on("error", function(err) {
// setImmediate here because errors can be emitted during the first call to pipe()
setImmediate(function() {
if (!destroyed) inflateFilter.emit("error", err);
});
});
var checkerStream = new AssertByteCountStream(entry.uncompressedSize);
inflateFilter.on("error", function(err) {
// forward zlib errors to the client-visible stream
setImmediate(function() {
if (!destroyed) checkerStream.emit("error", err);
});
});
checkerStream.destroy = function() {
destroyed = true;
inflateFilter.unpipe(checkerStream);
readStream.unpipe(inflateFilter);
// TODO: the inflateFilter now causes a memory leak. see Issue #27.
readStream.destroy();
};
endpointStream = readStream.pipe(inflateFilter).pipe(checkerStream);
}
callback(null, endpointStream);
} finally {
self.reader.unref();
}
});
};
function Entry() {
}
Entry.prototype.getLastModDate = function() {
return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime);
};
function dosDateTimeToDate(date, time) {
var day = date & 0x1f; // 1-31
var month = (date >> 5 & 0xf) - 1; // 1-12, 0-11
var year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108
var millisecond = 0;
var second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers)
var minute = time >> 5 & 0x3f; // 0-59
var hour = time >> 11 & 0x1f; // 0-23
return new Date(year, month, day, hour, minute, second, millisecond);
}
function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
if (length === 0) {
// fs.read will throw an out-of-bounds error if you try to read 0 bytes from a 0 byte file
return setImmediate(function() { callback(null, new Buffer(0)); });
}
reader.read(buffer, offset, length, position, function(err, bytesRead) {
if (err) return callback(err);
if (bytesRead < length) return callback(new Error("unexpected EOF"));
callback();
});
}
util.inherits(AssertByteCountStream, Transform);
function AssertByteCountStream(byteCount) {
Transform.call(this);
this.actualByteCount = 0;
this.expectedByteCount = byteCount;
}
AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
this.actualByteCount += chunk.length;
if (this.actualByteCount > this.expectedByteCount) {
var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
return cb(new Error(msg));
}
cb(null, chunk);
};
AssertByteCountStream.prototype._flush = function(cb) {
if (this.actualByteCount < this.expectedByteCount) {
var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
return cb(new Error(msg));
}
cb();
};
util.inherits(RandomAccessReader, EventEmitter);
function RandomAccessReader() {
EventEmitter.call(this);
this.refCount = 0;
}
RandomAccessReader.prototype.ref = function() {
this.refCount += 1;
};
RandomAccessReader.prototype.unref = function() {
var self = this;
self.refCount -= 1;
if (self.refCount > 0) return;
if (self.refCount < 0) throw new Error("invalid unref");
self.close(onCloseDone);
function onCloseDone(err) {
if (err) return self.emit('error', err);
self.emit('close');
}
};
RandomAccessReader.prototype.createReadStream = function(options) {
var start = options.start;
var end = options.end;
if (start === end) {
var emptyStream = new PassThrough();
setImmediate(function() {
emptyStream.end();
});
return emptyStream;
}
var stream = this._readStreamForRange(start, end);
var destroyed = false;
var refUnrefFilter = new RefUnrefFilter(this);
stream.on("error", function(err) {
setImmediate(function() {
if (!destroyed) refUnrefFilter.emit("error", err);
});
});
refUnrefFilter.destroy = function() {
stream.unpipe(refUnrefFilter);
refUnrefFilter.unref();
stream.destroy();
};
var byteCounter = new AssertByteCountStream(end - start);
refUnrefFilter.on("error", function(err) {
setImmediate(function() {
if (!destroyed) byteCounter.emit("error", err);
});
});
byteCounter.destroy = function() {
destroyed = true;
refUnrefFilter.unpipe(byteCounter);
refUnrefFilter.destroy();
};
return stream.pipe(refUnrefFilter).pipe(byteCounter);
};
RandomAccessReader.prototype._readStreamForRange = function(start, end) {
throw new Error("not implemented");
};
RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
var readStream = this.createReadStream({start: position, end: position + length});
var writeStream = new Writable();
var written = 0;
writeStream._write = function(chunk, encoding, cb) {
chunk.copy(buffer, offset + written, 0, chunk.length);
written += chunk.length;
cb();
};
writeStream.on("finish", callback);
readStream.on("error", function(error) {
callback(error);
});
readStream.pipe(writeStream);
};
RandomAccessReader.prototype.close = function(callback) {
setImmediate(callback);
};
util.inherits(RefUnrefFilter, PassThrough);
function RefUnrefFilter(context) {
PassThrough.call(this);
this.context = context;
this.context.ref();
this.unreffedYet = false;
}
RefUnrefFilter.prototype._flush = function(cb) {
this.unref();
cb();
};
RefUnrefFilter.prototype.unref = function(cb) {
if (this.unreffedYet) return;
this.unreffedYet = true;
this.context.unref();
};
var cp437 = '\u0000 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
function bufferToString(buffer, start, end, isUtf8) {
if (isUtf8) {
return buffer.toString("utf8", start, end);
} else {
var result = "";
for (var i = start; i < end; i++) {
result += cp437[buffer[i]];
}
return result;
}
}
function readUInt64LE(buffer, offset) {
// there is no native function for this, because we can't actually store 64-bit integers precisely.
// after 53 bits, JavaScript's Number type (IEEE 754 double) can't store individual integers anymore.
// but since 53 bits is a whole lot more than 32 bits, we do our best anyway.
var lower32 = buffer.readUInt32LE(offset);
var upper32 = buffer.readUInt32LE(offset + 4);
// we can't use bitshifting here, because JavaScript bitshifting only works on 32-bit integers.
return upper32 * 0x100000000 + lower32;
// as long as we're bounds checking the result of this function against the total file size,
// we'll catch any overflow errors, because we already made sure the total file size was within reason.
}
function defaultCallback(err) {
if (err) throw err;
}
``` | /content/code_sandbox/node_modules/yauzl/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 6,280 |
```javascript
// Generated by LiveScript 1.2.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
types = {
'*': function(it){
switch (toString$.call(it).slice(8, -1)) {
case 'Array':
return coerceType(it, {
type: 'Array'
});
case 'Object':
return coerceType(it, {
type: 'Object'
});
default:
return {
type: 'Just',
value: coerceTypes(it, [
{
type: 'Undefined'
}, {
type: 'Null'
}, {
type: 'NaN'
}, {
type: 'Boolean'
}, {
type: 'Number'
}, {
type: 'Date'
}, {
type: 'RegExp'
}, {
type: 'Array'
}, {
type: 'Object'
}, {
type: 'String'
}
], {
explicit: true
})
};
}
},
Undefined: function(it){
if (it === 'undefined' || it === void 8) {
return {
type: 'Just',
value: void 8
};
} else {
return {
type: 'Nothing'
};
}
},
Null: function(it){
if (it === 'null') {
return {
type: 'Just',
value: null
};
} else {
return {
type: 'Nothing'
};
}
},
NaN: function(it){
if (it === 'NaN') {
return {
type: 'Just',
value: NaN
};
} else {
return {
type: 'Nothing'
};
}
},
Boolean: function(it){
if (it === 'true') {
return {
type: 'Just',
value: true
};
} else if (it === 'false') {
return {
type: 'Just',
value: false
};
} else {
return {
type: 'Nothing'
};
}
},
Number: function(it){
return {
type: 'Just',
value: +it
};
},
Int: function(it){
return {
type: 'Just',
value: parseInt(it)
};
},
Float: function(it){
return {
type: 'Just',
value: parseFloat(it)
};
},
Date: function(value, options){
var that;
if (that = /^\#(.*)\#$/.exec(value)) {
return {
type: 'Just',
value: new Date(+that[1] || that[1])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new Date(+value || value)
};
}
},
RegExp: function(value, options){
var that;
if (that = /^\/(.*)\/([gimy]*)$/.exec(value)) {
return {
type: 'Just',
value: new RegExp(that[1], that[2])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new RegExp(value)
};
}
},
Array: function(it){
return coerceArray(it, {
of: [{
type: '*'
}]
});
},
Object: function(it){
return coerceFields(it, {
of: {}
});
},
String: function(it){
var that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
if (that = it.match(/^'(.*)'$/)) {
return {
type: 'Just',
value: that[1]
};
} else if (that = it.match(/^"(.*)"$/)) {
return {
type: 'Just',
value: that[1]
};
} else {
return {
type: 'Just',
value: it
};
}
}
};
function coerceArray(node, type){
var typeOf, element;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
element = ref$[i$];
results$.push(coerceTypes(element, typeOf));
}
return results$;
}())
};
}
function coerceTuple(node, type){
var result, i$, ref$, len$, i, types, that;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
result = [];
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
i = i$;
types = ref$[i$];
if (that = coerceTypes(node[i], types)) {
result.push(that);
}
}
return {
type: 'Just',
value: result
};
}
function coerceFields(node, type){
var typeOf, key, value;
if (toString$.call(node).slice(8, -1) !== 'Object') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var ref$, results$ = {};
for (key in ref$ = node) {
value = ref$[key];
results$[key] = coerceTypes(value, typeOf[key] || [{
type: '*'
}]);
}
return results$;
}())
};
}
function coerceType(node, typeObj, options){
var type, structure, coerceFunc;
type = typeObj.type, structure = typeObj.structure;
if (type) {
coerceFunc = types[type];
return coerceFunc(node, options);
} else {
switch (structure) {
case 'array':
return coerceArray(node, typeObj);
case 'tuple':
return coerceTuple(node, typeObj);
case 'fields':
return coerceFields(node, typeObj);
}
}
}
function coerceTypes(node, types, options){
var i$, len$, type, ref$, valueType, value;
for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
type = types[i$];
ref$ = coerceType(node, type, options), valueType = ref$.type, value = ref$.value;
if (valueType === 'Nothing') {
continue;
}
if (parsedTypeCheck([type], value)) {
return value;
}
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = coerceTypes;
}).call(this);
``` | /content/code_sandbox/node_modules/levn/lib/coerce.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,641 |
```javascript
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var gulp = require('gulp'),
git = require('gulp-git'),
bump = require('gulp-bump'),
filter = require('gulp-filter'),
tagVersion = require('gulp-tag-version');
var TEST = [ 'test/*.js' ];
var POWERED = [ 'powered-test/*.js' ];
var SOURCE = [ 'src/**/*.js' ];
/**
* Bumping version number and tagging the repository with it.
* Please read path_to_url
*
* You can use the commands
*
* gulp patch # makes v0.1.0 -> v0.1.1
* gulp feature # makes v0.1.1 -> v0.2.0
* gulp release # makes v0.2.1 -> v1.0.0
*
* To bump the version numbers accordingly after you did a patch,
* introduced a feature or made a backwards-incompatible release.
*/
function inc(importance) {
// get all the files to bump version in
return gulp.src(['./package.json'])
// bump the version number in those files
.pipe(bump({type: importance}))
// save it back to filesystem
.pipe(gulp.dest('./'))
// commit the changed version number
.pipe(git.commit('Bumps package version'))
// read only one file to get the version number
.pipe(filter('package.json'))
// **tag it in the repository**
.pipe(tagVersion({
prefix: ''
}));
}
gulp.task('patch', [ ], function () { return inc('patch'); })
gulp.task('minor', [ ], function () { return inc('minor'); })
gulp.task('major', [ ], function () { return inc('major'); })
``` | /content/code_sandbox/node_modules/estraverse/gulpfile.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 617 |
```javascript
'use strict';
/* eslint-disable sort-keys */
module.exports = Object.freeze({
// same as DOM DOCUMENT_POSITION_
DISCONNECTED: 1,
PRECEDING: 2,
FOLLOWING: 4,
CONTAINS: 8,
CONTAINED_BY: 16,
});
``` | /content/code_sandbox/node_modules/symbol-tree/lib/TreePosition.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 63 |
```javascript
'use strict';
const TREE = Symbol();
const ROOT = Symbol();
const NEXT = Symbol();
const ITERATE_FUNC = Symbol();
class TreeIterator {
constructor(tree, root, firstResult, iterateFunction) {
this[TREE] = tree;
this[ROOT] = root;
this[NEXT] = firstResult;
this[ITERATE_FUNC] = iterateFunction;
}
next() {
const tree = this[TREE];
const iterateFunc = this[ITERATE_FUNC];
const root = this[ROOT];
if (!this[NEXT]) {
return {
done: true,
value: root,
};
}
const value = this[NEXT];
if (iterateFunc === 1) {
this[NEXT] = tree._node(value).previousSibling;
}
else if (iterateFunc === 2) {
this[NEXT] = tree._node(value).nextSibling;
}
else if (iterateFunc === 3) {
this[NEXT] = tree._node(value).parent;
}
else if (iterateFunc === 4) {
this[NEXT] = tree.preceding(value, {root: root});
}
else /* if (iterateFunc === 5)*/ {
this[NEXT] = tree.following(value, {root: root});
}
return {
done: false,
value: value,
};
}
}
Object.defineProperty(TreeIterator.prototype, Symbol.iterator, {
value: function() {
return this;
},
writable: false,
});
TreeIterator.PREV = 1;
TreeIterator.NEXT = 2;
TreeIterator.PARENT = 3;
TreeIterator.PRECEDING = 4;
TreeIterator.FOLLOWING = 5;
Object.freeze(TreeIterator);
Object.freeze(TreeIterator.prototype);
module.exports = TreeIterator;
``` | /content/code_sandbox/node_modules/symbol-tree/lib/TreeIterator.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 391 |
```javascript
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint vars:false, bitwise:true*/
/*jshint indent:4*/
/*global exports:true*/
(function clone(exports) {
'use strict';
var Syntax,
isArray,
VisitorOption,
VisitorKeys,
objectCreate,
objectKeys,
BREAK,
SKIP,
REMOVE;
function ignoreJSHintError() { }
isArray = Array.isArray;
if (!isArray) {
isArray = function isArray(array) {
return Object.prototype.toString.call(array) === '[object Array]';
};
}
function deepCopy(obj) {
var ret = {}, key, val;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
val = obj[key];
if (typeof val === 'object' && val !== null) {
ret[key] = deepCopy(val);
} else {
ret[key] = val;
}
}
}
return ret;
}
function shallowCopy(obj) {
var ret = {}, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = obj[key];
}
}
return ret;
}
ignoreJSHintError(shallowCopy);
// based on LLVM libc++ upper_bound / lower_bound
function upperBound(array, func) {
var diff, len, i, current;
len = array.length;
i = 0;
while (len) {
diff = len >>> 1;
current = i + diff;
if (func(array[current])) {
len = diff;
} else {
i = current + 1;
len -= diff + 1;
}
}
return i;
}
function lowerBound(array, func) {
var diff, len, i, current;
len = array.length;
i = 0;
while (len) {
diff = len >>> 1;
current = i + diff;
if (func(array[current])) {
i = current + 1;
len -= diff + 1;
} else {
len = diff;
}
}
return i;
}
ignoreJSHintError(lowerBound);
objectCreate = Object.create || (function () {
function F() { }
return function (o) {
F.prototype = o;
return new F();
};
})();
objectKeys = Object.keys || function (o) {
var keys = [], key;
for (key in o) {
keys.push(key);
}
return keys;
};
function extend(to, from) {
var keys = objectKeys(from), key, i, len;
for (i = 0, len = keys.length; i < len; i += 1) {
key = keys[i];
to[key] = from[key];
}
return to;
}
Syntax = {
AssignmentExpression: 'AssignmentExpression',
AssignmentPattern: 'AssignmentPattern',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DirectiveStatement: 'DirectiveStatement',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportAllDeclaration: 'ExportAllDeclaration',
ExportDefaultDeclaration: 'ExportDefaultDeclaration',
ExportNamedDeclaration: 'ExportNamedDeclaration',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MetaProperty: 'MetaProperty',
MethodDefinition: 'MethodDefinition',
ModuleSpecifier: 'ModuleSpecifier',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
Program: 'Program',
Property: 'Property',
RestElement: 'RestElement',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
Super: 'Super',
SwitchStatement: 'SwitchStatement',
SwitchCase: 'SwitchCase',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
YieldExpression: 'YieldExpression'
};
VisitorKeys = {
AssignmentExpression: ['left', 'right'],
AssignmentPattern: ['left', 'right'],
ArrayExpression: ['elements'],
ArrayPattern: ['elements'],
ArrowFunctionExpression: ['params', 'body'],
AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
BlockStatement: ['body'],
BinaryExpression: ['left', 'right'],
BreakStatement: ['label'],
CallExpression: ['callee', 'arguments'],
CatchClause: ['param', 'body'],
ClassBody: ['body'],
ClassDeclaration: ['id', 'superClass', 'body'],
ClassExpression: ['id', 'superClass', 'body'],
ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
ConditionalExpression: ['test', 'consequent', 'alternate'],
ContinueStatement: ['label'],
DebuggerStatement: [],
DirectiveStatement: [],
DoWhileStatement: ['body', 'test'],
EmptyStatement: [],
ExportAllDeclaration: ['source'],
ExportDefaultDeclaration: ['declaration'],
ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
ExportSpecifier: ['exported', 'local'],
ExpressionStatement: ['expression'],
ForStatement: ['init', 'test', 'update', 'body'],
ForInStatement: ['left', 'right', 'body'],
ForOfStatement: ['left', 'right', 'body'],
FunctionDeclaration: ['id', 'params', 'body'],
FunctionExpression: ['id', 'params', 'body'],
GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
Identifier: [],
IfStatement: ['test', 'consequent', 'alternate'],
ImportDeclaration: ['specifiers', 'source'],
ImportDefaultSpecifier: ['local'],
ImportNamespaceSpecifier: ['local'],
ImportSpecifier: ['imported', 'local'],
Literal: [],
LabeledStatement: ['label', 'body'],
LogicalExpression: ['left', 'right'],
MemberExpression: ['object', 'property'],
MetaProperty: ['meta', 'property'],
MethodDefinition: ['key', 'value'],
ModuleSpecifier: [],
NewExpression: ['callee', 'arguments'],
ObjectExpression: ['properties'],
ObjectPattern: ['properties'],
Program: ['body'],
Property: ['key', 'value'],
RestElement: [ 'argument' ],
ReturnStatement: ['argument'],
SequenceExpression: ['expressions'],
SpreadElement: ['argument'],
Super: [],
SwitchStatement: ['discriminant', 'cases'],
SwitchCase: ['test', 'consequent'],
TaggedTemplateExpression: ['tag', 'quasi'],
TemplateElement: [],
TemplateLiteral: ['quasis', 'expressions'],
ThisExpression: [],
ThrowStatement: ['argument'],
TryStatement: ['block', 'handler', 'finalizer'],
UnaryExpression: ['argument'],
UpdateExpression: ['argument'],
VariableDeclaration: ['declarations'],
VariableDeclarator: ['id', 'init'],
WhileStatement: ['test', 'body'],
WithStatement: ['object', 'body'],
YieldExpression: ['argument']
};
// unique id
BREAK = {};
SKIP = {};
REMOVE = {};
VisitorOption = {
Break: BREAK,
Skip: SKIP,
Remove: REMOVE
};
function Reference(parent, key) {
this.parent = parent;
this.key = key;
}
Reference.prototype.replace = function replace(node) {
this.parent[this.key] = node;
};
Reference.prototype.remove = function remove() {
if (isArray(this.parent)) {
this.parent.splice(this.key, 1);
return true;
} else {
this.replace(null);
return false;
}
};
function Element(node, path, wrap, ref) {
this.node = node;
this.path = path;
this.wrap = wrap;
this.ref = ref;
}
function Controller() { }
// API:
// return property path array from root to current node
Controller.prototype.path = function path() {
var i, iz, j, jz, result, element;
function addToPath(result, path) {
if (isArray(path)) {
for (j = 0, jz = path.length; j < jz; ++j) {
result.push(path[j]);
}
} else {
result.push(path);
}
}
// root node
if (!this.__current.path) {
return null;
}
// first node is sentinel, second node is root element
result = [];
for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
element = this.__leavelist[i];
addToPath(result, element.path);
}
addToPath(result, this.__current.path);
return result;
};
// API:
// return type of current node
Controller.prototype.type = function () {
var node = this.current();
return node.type || this.__current.wrap;
};
// API:
// return array of parent elements
Controller.prototype.parents = function parents() {
var i, iz, result;
// first node is sentinel
result = [];
for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
result.push(this.__leavelist[i].node);
}
return result;
};
// API:
// return current node
Controller.prototype.current = function current() {
return this.__current.node;
};
Controller.prototype.__execute = function __execute(callback, element) {
var previous, result;
result = undefined;
previous = this.__current;
this.__current = element;
this.__state = null;
if (callback) {
result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
}
this.__current = previous;
return result;
};
// API:
// notify control skip / break
Controller.prototype.notify = function notify(flag) {
this.__state = flag;
};
// API:
// skip child nodes of current node
Controller.prototype.skip = function () {
this.notify(SKIP);
};
// API:
// break traversals
Controller.prototype['break'] = function () {
this.notify(BREAK);
};
// API:
// remove node
Controller.prototype.remove = function () {
this.notify(REMOVE);
};
Controller.prototype.__initialize = function(root, visitor) {
this.visitor = visitor;
this.root = root;
this.__worklist = [];
this.__leavelist = [];
this.__current = null;
this.__state = null;
this.__fallback = null;
if (visitor.fallback === 'iteration') {
this.__fallback = objectKeys;
} else if (typeof visitor.fallback === 'function') {
this.__fallback = visitor.fallback;
}
this.__keys = VisitorKeys;
if (visitor.keys) {
this.__keys = extend(objectCreate(this.__keys), visitor.keys);
}
};
function isNode(node) {
if (node == null) {
return false;
}
return typeof node === 'object' && typeof node.type === 'string';
}
function isProperty(nodeType, key) {
return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
}
Controller.prototype.traverse = function traverse(root, visitor) {
var worklist,
leavelist,
element,
node,
nodeType,
ret,
key,
current,
current2,
candidates,
candidate,
sentinel;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
worklist.push(new Element(root, null, null, null));
leavelist.push(new Element(null, null, null, null));
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
ret = this.__execute(visitor.leave, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
continue;
}
if (element.node) {
ret = this.__execute(visitor.enter, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || ret === SKIP) {
continue;
}
node = element.node;
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', null);
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, null);
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, null));
}
}
}
}
};
Controller.prototype.replace = function replace(root, visitor) {
var worklist,
leavelist,
node,
nodeType,
target,
element,
current,
current2,
candidates,
candidate,
sentinel,
outer,
key;
function removeElem(element) {
var i,
key,
nextElem,
parent;
if (element.ref.remove()) {
// When the reference is an element of an array.
key = element.ref.key;
parent = element.ref.parent;
// If removed from array, then decrease following items' keys.
i = worklist.length;
while (i--) {
nextElem = worklist[i];
if (nextElem.ref && nextElem.ref.parent === parent) {
if (nextElem.ref.key < key) {
break;
}
--nextElem.ref.key;
}
}
}
}
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
outer = {
root: root
};
element = new Element(root, null, null, new Reference(outer, 'root'));
worklist.push(element);
leavelist.push(element);
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
target = this.__execute(visitor.leave, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
continue;
}
target = this.__execute(visitor.enter, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
element.node = target;
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
element.node = null;
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
// node may be null
node = element.node;
if (!node) {
continue;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || target === SKIP) {
continue;
}
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, new Reference(node, key)));
}
}
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
function extendCommentRange(comment, tokens) {
var target;
target = upperBound(tokens, function search(token) {
return token.range[0] > comment.range[0];
});
comment.extendedRange = [comment.range[0], comment.range[1]];
if (target !== tokens.length) {
comment.extendedRange[1] = tokens[target].range[0];
}
target -= 1;
if (target >= 0) {
comment.extendedRange[0] = tokens[target].range[1];
}
return comment;
}
function attachComments(tree, providedComments, tokens) {
// At first, we should calculate extended comment ranges.
var comments = [], comment, len, i, cursor;
if (!tree.range) {
throw new Error('attachComments needs range information');
}
// tokens array is empty, we attach comments to tree as 'leadingComments'
if (!tokens.length) {
if (providedComments.length) {
for (i = 0, len = providedComments.length; i < len; i += 1) {
comment = deepCopy(providedComments[i]);
comment.extendedRange = [0, tree.range[0]];
comments.push(comment);
}
tree.leadingComments = comments;
}
return tree;
}
for (i = 0, len = providedComments.length; i < len; i += 1) {
comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
}
// This is based on John Freeman's implementation.
cursor = 0;
traverse(tree, {
enter: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (comment.extendedRange[1] > node.range[0]) {
break;
}
if (comment.extendedRange[1] === node.range[0]) {
if (!node.leadingComments) {
node.leadingComments = [];
}
node.leadingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
cursor = 0;
traverse(tree, {
leave: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (node.range[1] < comment.extendedRange[0]) {
break;
}
if (node.range[1] === comment.extendedRange[0]) {
if (!node.trailingComments) {
node.trailingComments = [];
}
node.trailingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
return tree;
}
exports.version = require('./package.json').version;
exports.Syntax = Syntax;
exports.traverse = traverse;
exports.replace = replace;
exports.attachComments = attachComments;
exports.VisitorKeys = VisitorKeys;
exports.VisitorOption = VisitorOption;
exports.Controller = Controller;
exports.cloneEnvironment = function () { return clone({}); };
return exports;
}(exports));
/* vim: set sw=4 ts=4 et tw=80 : */
``` | /content/code_sandbox/node_modules/estraverse/estraverse.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 5,428 |
```javascript
'use strict';
module.exports = class SymbolTreeNode {
constructor() {
this.parent = null;
this.previousSibling = null;
this.nextSibling = null;
this.firstChild = null;
this.lastChild = null;
/** This value is incremented anytime a children is added or removed */
this.childrenVersion = 0;
/** The last child object which has a cached index */
this.childIndexCachedUpTo = null;
/** This value represents the cached node index, as long as
* cachedIndexVersion matches with the childrenVersion of the parent */
this.cachedIndex = -1;
this.cachedIndexVersion = NaN; // NaN is never equal to anything
}
get isAttached() {
return Boolean(this.parent || this.previousSibling || this.nextSibling);
}
get hasChildren() {
return Boolean(this.firstChild);
}
childrenChanged() {
/* jshint -W016 */
// integer wrap around
this.childrenVersion = (this.childrenVersion + 1) & 0xFFFFFFFF;
this.childIndexCachedUpTo = null;
}
getCachedIndex(parentNode) {
// (assumes parentNode is actually the parent)
if (this.cachedIndexVersion !== parentNode.childrenVersion) {
this.cachedIndexVersion = NaN;
// cachedIndex is no longer valid
return -1;
}
return this.cachedIndex; // -1 if not cached
}
setCachedIndex(parentNode, index) {
// (assumes parentNode is actually the parent)
this.cachedIndexVersion = parentNode.childrenVersion;
this.cachedIndex = index;
}
};
``` | /content/code_sandbox/node_modules/symbol-tree/lib/SymbolTreeNode.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 348 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
var path = require('path');
var fs = require('fs');
var copy = require('dryice').copy;
function removeAmdefine(src) {
src = String(src).replace(
/if\s*\(typeof\s*define\s*!==\s*'function'\)\s*{\s*var\s*define\s*=\s*require\('amdefine'\)\(module,\s*require\);\s*}\s*/g,
'');
src = src.replace(
/\b(define\(.*)('amdefine',?)/gm,
'$1');
return src;
}
removeAmdefine.onRead = true;
function makeNonRelative(src) {
return src
.replace(/require\('.\//g, 'require(\'source-map/')
.replace(/\.\.\/\.\.\/lib\//g, '');
}
makeNonRelative.onRead = true;
function buildBrowser() {
console.log('\nCreating dist/source-map.js');
var project = copy.createCommonJsProject({
roots: [ path.join(__dirname, 'lib') ]
});
copy({
source: [
'build/mini-require.js',
{
project: project,
require: [ 'source-map/source-map-generator',
'source-map/source-map-consumer',
'source-map/source-node']
},
'build/suffix-browser.js'
],
filter: [
copy.filter.moduleDefines,
removeAmdefine
],
dest: 'dist/source-map.js'
});
}
function buildBrowserMin() {
console.log('\nCreating dist/source-map.min.js');
copy({
source: 'dist/source-map.js',
filter: copy.filter.uglifyjs,
dest: 'dist/source-map.min.js'
});
}
function buildFirefox() {
console.log('\nCreating dist/SourceMap.jsm');
var project = copy.createCommonJsProject({
roots: [ path.join(__dirname, 'lib') ]
});
copy({
source: [
'build/prefix-source-map.jsm',
{
project: project,
require: [ 'source-map/source-map-consumer',
'source-map/source-map-generator',
'source-map/source-node' ]
},
'build/suffix-source-map.jsm'
],
filter: [
copy.filter.moduleDefines,
removeAmdefine,
makeNonRelative
],
dest: 'dist/SourceMap.jsm'
});
// Create dist/test/Utils.jsm
console.log('\nCreating dist/test/Utils.jsm');
project = copy.createCommonJsProject({
roots: [ __dirname, path.join(__dirname, 'lib') ]
});
copy({
source: [
'build/prefix-utils.jsm',
'build/assert-shim.js',
{
project: project,
require: [ 'test/source-map/util' ]
},
'build/suffix-utils.jsm'
],
filter: [
copy.filter.moduleDefines,
removeAmdefine,
makeNonRelative
],
dest: 'dist/test/Utils.jsm'
});
function isTestFile(f) {
return /^test\-.*?\.js/.test(f);
}
var testFiles = fs.readdirSync(path.join(__dirname, 'test', 'source-map')).filter(isTestFile);
testFiles.forEach(function (testFile) {
console.log('\nCreating', path.join('dist', 'test', testFile.replace(/\-/g, '_')));
copy({
source: [
'build/test-prefix.js',
path.join('test', 'source-map', testFile),
'build/test-suffix.js'
],
filter: [
removeAmdefine,
makeNonRelative,
function (input, source) {
return input.replace('define(',
'define("'
+ path.join('test', 'source-map', testFile.replace(/\.js$/, ''))
+ '", ["require", "exports", "module"], ');
},
function (input, source) {
return input.replace('{THIS_MODULE}', function () {
return "test/source-map/" + testFile.replace(/\.js$/, '');
});
}
],
dest: path.join('dist', 'test', testFile.replace(/\-/g, '_'))
});
});
}
function ensureDir(name) {
var dirExists = false;
try {
dirExists = fs.statSync(name).isDirectory();
} catch (err) {}
if (!dirExists) {
fs.mkdirSync(name, 0777);
}
}
ensureDir("dist");
ensureDir("dist/test");
buildFirefox();
buildBrowser();
buildBrowserMin();
``` | /content/code_sandbox/node_modules/source-map/Makefile.dryice.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,010 |
```javascript
/*
* path_to_url
*/
exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./source-map/source-node').SourceNode;
``` | /content/code_sandbox/node_modules/source-map/lib/source-map.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 57 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the next
// closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return null.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return aHaystack[mid];
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0
? null
: aHaystack[aLow];
}
}
/**
* This is an implementation of binary search which will always try and return
* the next lowest value checked if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
: null;
};
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/binary-search.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 805 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* path_to_url
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string.
*/
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/base64-vlq.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,195 |
```javascript
'use strict';
/**
* @module symbol-tree
* @author Joris van der Wel <joris@jorisvanderwel.com>
*/
const SymbolTreeNode = require('./SymbolTreeNode');
const TreePosition = require('./TreePosition');
const TreeIterator = require('./TreeIterator');
function returnTrue() {
return true;
}
function reverseArrayIndex(array, reverseIndex) {
return array[array.length - 1 - reverseIndex]; // no need to check `index >= 0`
}
class SymbolTree {
/**
* @constructor
* @alias module:symbol-tree
* @param {string} [description='SymbolTree data'] Description used for the Symbol
*/
constructor(description) {
this.symbol = Symbol(description || 'SymbolTree data');
}
/**
* You can use this function to (optionally) initialize an object right after its creation,
* to take advantage of V8's fast properties. Also useful if you would like to
* freeze your object.
*
* `O(1)`
*
* @method
* @alias module:symbol-tree#initialize
* @param {Object} object
* @return {Object} object
*/
initialize(object) {
this._node(object);
return object;
}
_node(object) {
if (!object) {
return null;
}
const node = object[this.symbol];
if (node) {
return node;
}
return (object[this.symbol] = new SymbolTreeNode());
}
/**
* Returns `true` if the object has any children. Otherwise it returns `false`.
*
* * `O(1)`
*
* @method hasChildren
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Boolean}
*/
hasChildren(object) {
return this._node(object).hasChildren;
}
/**
* Returns the first child of the given object.
*
* * `O(1)`
*
* @method firstChild
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
firstChild(object) {
return this._node(object).firstChild;
}
/**
* Returns the last child of the given object.
*
* * `O(1)`
*
* @method lastChild
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
lastChild(object) {
return this._node(object).lastChild;
}
/**
* Returns the previous sibling of the given object.
*
* * `O(1)`
*
* @method previousSibling
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
previousSibling(object) {
return this._node(object).previousSibling;
}
/**
* Returns the next sibling of the given object.
*
* * `O(1)`
*
* @method nextSibling
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
nextSibling(object) {
return this._node(object).nextSibling;
}
/**
* Return the parent of the given object.
*
* * `O(1)`
*
* @method parent
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
parent(object) {
return this._node(object).parent;
}
/**
* Find the inclusive descendant that is last in tree order of the given object.
*
* * `O(n)` (worst case) where `n` is the depth of the subtree of `object`
*
* @method lastInclusiveDescendant
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
lastInclusiveDescendant(object) {
let lastChild;
let current = object;
while ((lastChild = this._node(current).lastChild)) {
current = lastChild;
}
return current;
}
/**
* Find the preceding object (A) of the given object (B).
* An object A is preceding an object B if A and B are in the same tree
* and A comes before B in tree order.
*
* * `O(n)` (worst case)
* * `O(1)` (amortized when walking the entire tree)
*
* @method preceding
* @memberOf module:symbol-tree#
* @param {Object} object
* @param {Object} [options]
* @param {Object} [options.root] If set, `root` must be an inclusive ancestor
* of the return value (or else null is returned). This check _assumes_
* that `root` is also an inclusive ancestor of the given `object`
* @return {?Object}
*/
preceding(object, options) {
const treeRoot = options && options.root;
if (object === treeRoot) {
return null;
}
const previousSibling = this._node(object).previousSibling;
if (previousSibling) {
return this.lastInclusiveDescendant(previousSibling);
}
// if there is no previous sibling return the parent (might be null)
return this._node(object).parent;
}
/**
* Find the following object (A) of the given object (B).
* An object A is following an object B if A and B are in the same tree
* and A comes after B in tree order.
*
* * `O(n)` (worst case) where `n` is the amount of objects in the entire tree
* * `O(1)` (amortized when walking the entire tree)
*
* @method following
* @memberOf module:symbol-tree#
* @param {!Object} object
* @param {Object} [options]
* @param {Object} [options.root] If set, `root` must be an inclusive ancestor
* of the return value (or else null is returned). This check _assumes_
* that `root` is also an inclusive ancestor of the given `object`
* @param {Boolean} [options.skipChildren=false] If set, ignore the children of `object`
* @return {?Object}
*/
following(object, options) {
const treeRoot = options && options.root;
const skipChildren = options && options.skipChildren;
const firstChild = !skipChildren && this._node(object).firstChild;
if (firstChild) {
return firstChild;
}
let current = object;
do {
if (current === treeRoot) {
return null;
}
const nextSibling = this._node(current).nextSibling;
if (nextSibling) {
return nextSibling;
}
current = this._node(current).parent;
} while (current);
return null;
}
/**
* Append all children of the given object to an array.
*
* * `O(n)` where `n` is the amount of children of the given `parent`
*
* @method childrenToArray
* @memberOf module:symbol-tree#
* @param {Object} parent
* @param {Object} [options]
* @param {Object[]} [options.array=[]]
* @param {Function} [options.filter] Function to test each object before it is added to the array.
* Invoked with arguments (object). Should return `true` if an object
* is to be included.
* @param {*} [options.thisArg] Value to use as `this` when executing `filter`.
* @return {Object[]}
*/
childrenToArray(parent, options) {
const array = (options && options.array) || [];
const filter = (options && options.filter) || returnTrue;
const thisArg = (options && options.thisArg) || undefined;
const parentNode = this._node(parent);
let object = parentNode.firstChild;
let index = 0;
while (object) {
const node = this._node(object);
node.setCachedIndex(parentNode, index);
if (filter.call(thisArg, object)) {
array.push(object);
}
object = node.nextSibling;
++index;
}
return array;
}
/**
* Append all inclusive ancestors of the given object to an array.
*
* * `O(n)` where `n` is the amount of ancestors of the given `object`
*
* @method ancestorsToArray
* @memberOf module:symbol-tree#
* @param {Object} object
* @param {Object} [options]
* @param {Object[]} [options.array=[]]
* @param {Function} [options.filter] Function to test each object before it is added to the array.
* Invoked with arguments (object). Should return `true` if an object
* is to be included.
* @param {*} [options.thisArg] Value to use as `this` when executing `filter`.
* @return {Object[]}
*/
ancestorsToArray(object, options) {
const array = (options && options.array) || [];
const filter = (options && options.filter) || returnTrue;
const thisArg = (options && options.thisArg) || undefined;
let ancestor = object;
while (ancestor) {
if (filter.call(thisArg, ancestor)) {
array.push(ancestor);
}
ancestor = this._node(ancestor).parent;
}
return array;
}
/**
* Append all descendants of the given object to an array (in tree order).
*
* * `O(n)` where `n` is the amount of objects in the sub-tree of the given `object`
*
* @method treeToArray
* @memberOf module:symbol-tree#
* @param {Object} root
* @param {Object} [options]
* @param {Object[]} [options.array=[]]
* @param {Function} [options.filter] Function to test each object before it is added to the array.
* Invoked with arguments (object). Should return `true` if an object
* is to be included.
* @param {*} [options.thisArg] Value to use as `this` when executing `filter`.
* @return {Object[]}
*/
treeToArray(root, options) {
const array = (options && options.array) || [];
const filter = (options && options.filter) || returnTrue;
const thisArg = (options && options.thisArg) || undefined;
let object = root;
while (object) {
if (filter.call(thisArg, object)) {
array.push(object);
}
object = this.following(object, {root: root});
}
return array;
}
/**
* Iterate over all children of the given object
*
* * `O(1)` for a single iteration
*
* @method childrenIterator
* @memberOf module:symbol-tree#
* @param {Object} parent
* @param {Object} [options]
* @param {Boolean} [options.reverse=false]
* @return {Object} An iterable iterator (ES6)
*/
childrenIterator(parent, options) {
const reverse = options && options.reverse;
const parentNode = this._node(parent);
return new TreeIterator(
this,
parent,
reverse ? parentNode.lastChild : parentNode.firstChild,
reverse ? TreeIterator.PREV : TreeIterator.NEXT
);
}
/**
* Iterate over all the previous siblings of the given object. (in reverse tree order)
*
* * `O(1)` for a single iteration
*
* @method previousSiblingsIterator
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object} An iterable iterator (ES6)
*/
previousSiblingsIterator(object) {
return new TreeIterator(
this,
object,
this._node(object).previousSibling,
TreeIterator.PREV
);
}
/**
* Iterate over all the next siblings of the given object. (in tree order)
*
* * `O(1)` for a single iteration
*
* @method nextSiblingsIterator
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object} An iterable iterator (ES6)
*/
nextSiblingsIterator(object) {
return new TreeIterator(
this,
object,
this._node(object).nextSibling,
TreeIterator.NEXT
);
}
/**
* Iterate over all inclusive ancestors of the given object
*
* * `O(1)` for a single iteration
*
* @method ancestorsIterator
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object} An iterable iterator (ES6)
*/
ancestorsIterator(object) {
return new TreeIterator(
this,
object,
object,
TreeIterator.PARENT
);
}
/**
* Iterate over all descendants of the given object (in tree order).
*
* Where `n` is the amount of objects in the sub-tree of the given `root`:
*
* * `O(n)` (worst case for a single iteration)
* * `O(n)` (amortized, when completing the iterator)
*
* @method treeIterator
* @memberOf module:symbol-tree#
* @param {Object} root
* @param {Object} options
* @param {Boolean} [options.reverse=false]
* @return {Object} An iterable iterator (ES6)
*/
treeIterator(root, options) {
const reverse = options && options.reverse;
return new TreeIterator(
this,
root,
reverse ? this.lastInclusiveDescendant(root) : root,
reverse ? TreeIterator.PRECEDING : TreeIterator.FOLLOWING
);
}
/**
* Find the index of the given object (the number of preceding siblings).
*
* * `O(n)` where `n` is the amount of preceding siblings
* * `O(1)` (amortized, if the tree is not modified)
*
* @method index
* @memberOf module:symbol-tree#
* @param {Object} child
* @return {Number} The number of preceding siblings, or -1 if the object has no parent
*/
index(child) {
const childNode = this._node(child);
const parentNode = this._node(childNode.parent);
if (!parentNode) {
// In principal, you could also find out the number of preceding siblings
// for objects that do not have a parent. This method limits itself only to
// objects that have a parent because that lets us optimize more.
return -1;
}
let currentIndex = childNode.getCachedIndex(parentNode);
if (currentIndex >= 0) {
return currentIndex;
}
currentIndex = 0;
let object = parentNode.firstChild;
if (parentNode.childIndexCachedUpTo) {
const cachedUpToNode = this._node(parentNode.childIndexCachedUpTo);
object = cachedUpToNode.nextSibling;
currentIndex = cachedUpToNode.getCachedIndex(parentNode) + 1;
}
while (object) {
const node = this._node(object);
node.setCachedIndex(parentNode, currentIndex);
if (object === child) {
break;
}
++currentIndex;
object = node.nextSibling;
}
parentNode.childIndexCachedUpTo = child;
return currentIndex;
}
/**
* Calculate the number of children.
*
* * `O(n)` where `n` is the amount of children
* * `O(1)` (amortized, if the tree is not modified)
*
* @method childrenCount
* @memberOf module:symbol-tree#
* @param {Object} parent
* @return {Number}
*/
childrenCount(parent) {
const parentNode = this._node(parent);
if (!parentNode.lastChild) {
return 0;
}
return this.index(parentNode.lastChild) + 1;
}
/**
* Compare the position of an object relative to another object. A bit set is returned:
*
* <ul>
* <li>DISCONNECTED : 1</li>
* <li>PRECEDING : 2</li>
* <li>FOLLOWING : 4</li>
* <li>CONTAINS : 8</li>
* <li>CONTAINED_BY : 16</li>
* </ul>
*
* The semantics are the same as compareDocumentPosition in DOM, with the exception that
* DISCONNECTED never occurs with any other bit.
*
* where `n` and `m` are the amount of ancestors of `left` and `right`;
* where `o` is the amount of children of the lowest common ancestor of `left` and `right`:
*
* * `O(n + m + o)` (worst case)
* * `O(n + m)` (amortized, if the tree is not modified)
*
* @method compareTreePosition
* @memberOf module:symbol-tree#
* @param {Object} left
* @param {Object} right
* @return {Number}
*/
compareTreePosition(left, right) {
// In DOM terms:
// left = reference / context object
// right = other
if (left === right) {
return 0;
}
/* jshint -W016 */
const leftAncestors = []; { // inclusive
let leftAncestor = left;
while (leftAncestor) {
if (leftAncestor === right) {
return TreePosition.CONTAINS | TreePosition.PRECEDING;
// other is ancestor of reference
}
leftAncestors.push(leftAncestor);
leftAncestor = this.parent(leftAncestor);
}
}
const rightAncestors = []; {
let rightAncestor = right;
while (rightAncestor) {
if (rightAncestor === left) {
return TreePosition.CONTAINED_BY | TreePosition.FOLLOWING;
}
rightAncestors.push(rightAncestor);
rightAncestor = this.parent(rightAncestor);
}
}
const root = reverseArrayIndex(leftAncestors, 0);
if (!root || root !== reverseArrayIndex(rightAncestors, 0)) {
// note: unlike DOM, preceding / following is not set here
return TreePosition.DISCONNECTED;
}
// find the lowest common ancestor
let commonAncestorIndex = 0;
const ancestorsMinLength = Math.min(leftAncestors.length, rightAncestors.length);
for (let i = 0; i < ancestorsMinLength; ++i) {
const leftAncestor = reverseArrayIndex(leftAncestors, i);
const rightAncestor = reverseArrayIndex(rightAncestors, i);
if (leftAncestor !== rightAncestor) {
break;
}
commonAncestorIndex = i;
}
// indexes within the common ancestor
const leftIndex = this.index(reverseArrayIndex(leftAncestors, commonAncestorIndex + 1));
const rightIndex = this.index(reverseArrayIndex(rightAncestors, commonAncestorIndex + 1));
return rightIndex < leftIndex
? TreePosition.PRECEDING
: TreePosition.FOLLOWING;
}
/**
* Remove the object from this tree.
* Has no effect if already removed.
*
* * `O(1)`
*
* @method remove
* @memberOf module:symbol-tree#
* @param {Object} removeObject
* @return {Object} removeObject
*/
remove(removeObject) {
const removeNode = this._node(removeObject);
const parentNode = this._node(removeNode.parent);
const prevNode = this._node(removeNode.previousSibling);
const nextNode = this._node(removeNode.nextSibling);
if (parentNode) {
if (parentNode.firstChild === removeObject) {
parentNode.firstChild = removeNode.nextSibling;
}
if (parentNode.lastChild === removeObject) {
parentNode.lastChild = removeNode.previousSibling;
}
}
if (prevNode) {
prevNode.nextSibling = removeNode.nextSibling;
}
if (nextNode) {
nextNode.previousSibling = removeNode.previousSibling;
}
removeNode.parent = null;
removeNode.previousSibling = null;
removeNode.nextSibling = null;
removeNode.cachedIndex = -1;
removeNode.cachedIndexVersion = NaN;
if (parentNode) {
parentNode.childrenChanged();
}
return removeObject;
}
/**
* Insert the given object before the reference object.
* `newObject` is now the previous sibling of `referenceObject`.
*
* * `O(1)`
*
* @method insertBefore
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
insertBefore(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const prevNode = this._node(referenceNode.previousSibling);
const newNode = this._node(newObject);
const parentNode = this._node(referenceNode.parent);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
newNode.parent = referenceNode.parent;
newNode.previousSibling = referenceNode.previousSibling;
newNode.nextSibling = referenceObject;
referenceNode.previousSibling = newObject;
if (prevNode) {
prevNode.nextSibling = newObject;
}
if (parentNode && parentNode.firstChild === referenceObject) {
parentNode.firstChild = newObject;
}
if (parentNode) {
parentNode.childrenChanged();
}
return newObject;
}
/**
* Insert the given object after the reference object.
* `newObject` is now the next sibling of `referenceObject`.
*
* * `O(1)`
*
* @method insertAfter
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
insertAfter(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const nextNode = this._node(referenceNode.nextSibling);
const newNode = this._node(newObject);
const parentNode = this._node(referenceNode.parent);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
newNode.parent = referenceNode.parent;
newNode.previousSibling = referenceObject;
newNode.nextSibling = referenceNode.nextSibling;
referenceNode.nextSibling = newObject;
if (nextNode) {
nextNode.previousSibling = newObject;
}
if (parentNode && parentNode.lastChild === referenceObject) {
parentNode.lastChild = newObject;
}
if (parentNode) {
parentNode.childrenChanged();
}
return newObject;
}
/**
* Insert the given object as the first child of the given reference object.
* `newObject` is now the first child of `referenceObject`.
*
* * `O(1)`
*
* @method prependChild
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
prependChild(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const newNode = this._node(newObject);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
if (referenceNode.hasChildren) {
this.insertBefore(referenceNode.firstChild, newObject);
}
else {
newNode.parent = referenceObject;
referenceNode.firstChild = newObject;
referenceNode.lastChild = newObject;
referenceNode.childrenChanged();
}
return newObject;
}
/**
* Insert the given object as the last child of the given reference object.
* `newObject` is now the last child of `referenceObject`.
*
* * `O(1)`
*
* @method appendChild
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
appendChild(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const newNode = this._node(newObject);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
if (referenceNode.hasChildren) {
this.insertAfter(referenceNode.lastChild, newObject);
}
else {
newNode.parent = referenceObject;
referenceNode.firstChild = newObject;
referenceNode.lastChild = newObject;
referenceNode.childrenChanged();
}
return newObject;
}
}
module.exports = SymbolTree;
SymbolTree.TreePosition = TreePosition;
``` | /content/code_sandbox/node_modules/symbol-tree/lib/SymbolTree.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 5,688 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. To create a new one, you must pass an object
* with the following properties:
*
* - file: The filename of the generated source.
* - sourceRoot: An optional root for all URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file');
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source) {
newMapping.source = mapping.source;
if (sourceRoot) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent !== null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = {};
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (!aSourceFile) {
aSourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "aSourceFile" relative if an absolute Url is passed.
if (sourceRoot) {
aSourceFile = util.relative(sourceRoot, aSourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "aSourceFile"
this._mappings.forEach(function (mapping) {
if (mapping.source === aSourceFile && mapping.originalLine) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source !== null) {
// Copy mapping
if (sourceRoot) {
mapping.source = util.relative(sourceRoot, original.source);
} else {
mapping.source = original.source;
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name !== null && mapping.name !== null) {
// Only use the identifier name if it's an identifier
// in both SourceMaps
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
if (sourceRoot) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
orginal: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
// The mappings must be guaranteed to be in sorted order before we start
// serializing them or else the generated line numbers (which are defined
// via the ';' separators) will be all messed up. Note: it might be more
// performant to maintain the sorting as we insert them, rather than as we
// serialize them, but the big O is the same either way.
this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
continue;
}
result += ',';
}
}
result += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
- previousSource);
previousSource = this._sources.indexOf(mapping.source);
// lines are stored 0-based in SourceMap spec version 3
result += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
result += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/source-map-generator.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,829 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var util = require('./util');
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/array-set.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 666 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine === undefined ? null : aLine;
this.column = aColumn === undefined ? null : aColumn;
this.source = aSource === undefined ? null : aSource;
this.name = aName === undefined ? null : aName;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// The generated code
// Processed fragments are removed from this array.
var remainingLines = aGeneratedCode.split('\n');
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping === null) {
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(remainingLines.shift() + "\n");
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
} else {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
var code = "";
// Associate full lines with "lastMapping"
do {
code += remainingLines.shift() + "\n";
lastGeneratedLine++;
lastGeneratedColumn = 0;
} while (lastGeneratedLine < mapping.generatedLine);
// When we reached the correct line, we add code until we
// reach the correct column too.
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
code += nextLine.substr(0, mapping.generatedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
// Create the SourceNode.
addMappingWithCode(lastMapping, code);
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
}
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
// Associate the remaining code in the current line with "lastMapping"
// and add the remaining lines without any mapping
addMappingWithCode(lastMapping, remainingLines.join("\n"));
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
mapping.source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i] instanceof SourceNode) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
chunk.split('').forEach(function (ch) {
if (ch === '\n') {
generated.line++;
generated.column = 0;
} else {
generated.column++;
}
});
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/source-node.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,776 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/base64.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 269 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See path_to_url and
* path_to_url
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/util.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,358 |
```javascript
#!/usr/bin/env node
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var util = require('./source-map/util');
function run(tests) {
var failures = [];
var total = 0;
var passed = 0;
for (var i = 0; i < tests.length; i++) {
for (var k in tests[i].testCase) {
if (/^test/.test(k)) {
total++;
try {
tests[i].testCase[k](assert, util);
passed++;
}
catch (e) {
console.log('FAILED ' + tests[i].name + ': ' + k + '!');
console.log(e.stack);
}
}
}
}
console.log("");
console.log(passed + ' / ' + total + ' tests passed.');
console.log("");
failures.forEach(function (f) {
});
return failures.length;
}
var code;
process.stdout.on('close', function () {
process.exit(code);
});
function isTestFile(f) {
var testToRun = process.argv[2];
return testToRun
? path.basename(testToRun) === f
: /^test\-.*?\.js/.test(f);
}
function toModule(f) {
return './source-map/' + f.replace(/\.js$/, '');
}
var requires = fs.readdirSync(path.join(__dirname, 'source-map'))
.filter(isTestFile)
.map(toModule);
code = run(requires.map(require).map(function (mod, i) {
return {
name: requires[i],
testCase: mod
};
}));
process.exit(code);
``` | /content/code_sandbox/node_modules/source-map/test/run-tests.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 377 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var ArraySet = require('../../lib/source-map/array-set').ArraySet;
function makeTestSet() {
var set = new ArraySet();
for (var i = 0; i < 100; i++) {
set.add(String(i));
}
return set;
}
exports['test .has() membership'] = function (assert, util) {
var set = makeTestSet();
for (var i = 0; i < 100; i++) {
assert.ok(set.has(String(i)));
}
};
exports['test .indexOf() elements'] = function (assert, util) {
var set = makeTestSet();
for (var i = 0; i < 100; i++) {
assert.strictEqual(set.indexOf(String(i)), i);
}
};
exports['test .at() indexing'] = function (assert, util) {
var set = makeTestSet();
for (var i = 0; i < 100; i++) {
assert.strictEqual(set.at(i), String(i));
}
};
exports['test creating from an array'] = function (assert, util) {
var set = ArraySet.fromArray(['foo', 'bar', 'baz', 'quux', 'hasOwnProperty']);
assert.ok(set.has('foo'));
assert.ok(set.has('bar'));
assert.ok(set.has('baz'));
assert.ok(set.has('quux'));
assert.ok(set.has('hasOwnProperty'));
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.indexOf('bar'), 1);
assert.strictEqual(set.indexOf('baz'), 2);
assert.strictEqual(set.indexOf('quux'), 3);
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.at(1), 'bar');
assert.strictEqual(set.at(2), 'baz');
assert.strictEqual(set.at(3), 'quux');
};
exports['test that you can add __proto__; see github issue #30'] = function (assert, util) {
var set = new ArraySet();
set.add('__proto__');
assert.ok(set.has('__proto__'));
assert.strictEqual(set.at(0), '__proto__');
assert.strictEqual(set.indexOf('__proto__'), 0);
};
exports['test .fromArray() with duplicates'] = function (assert, util) {
var set = ArraySet.fromArray(['foo', 'foo']);
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 1);
set = ArraySet.fromArray(['foo', 'foo'], true);
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.at(1), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 2);
};
exports['test .add() with duplicates'] = function (assert, util) {
var set = new ArraySet();
set.add('foo');
set.add('foo');
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 1);
set.add('foo', true);
assert.ok(set.has('foo'));
assert.strictEqual(set.at(0), 'foo');
assert.strictEqual(set.at(1), 'foo');
assert.strictEqual(set.indexOf('foo'), 0);
assert.strictEqual(set.toArray().length, 2);
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-array-set.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 820 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var util = require('./util');
var binarySearch = require('./binary-search');
var ArraySet = require('./array-set').ArraySet;
var base64VLQ = require('./base64-vlq');
/**
* A SourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: path_to_url#
*/
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
/**
* Create a SourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns SourceMapConsumer
*/
SourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(SourceMapConsumer.prototype);
smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
smc.__generatedMappings = aSourceMap._mappings.slice()
.sort(util.compareByGeneratedPositions);
smc.__originalMappings = aSourceMap._mappings.slice()
.sort(util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
get: function () {
return this._sources.toArray().map(function (s) {
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function () {
if (!this.__generatedMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function () {
if (!this.__originalMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
}
else if (str.charAt(0) === ',') {
str = str.slice(1);
}
else {
mapping = {};
mapping.generatedLine = generatedLine;
// Generated column.
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
mapping.source = this._sources.at(previousSource + temp.value);
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
// Original line.
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
// Original column.
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original name.
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this.__generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
this.__originalMappings.push(mapping);
}
}
}
this.__originalMappings.sort(util.compareByOriginalPositions);
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
SourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator);
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
SourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var mapping = this._findMapping(needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
util.compareByGeneratedPositions);
if (mapping) {
var source = util.getArg(mapping, 'source', null);
if (source && this.sourceRoot) {
source = util.join(this.sourceRoot, source);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* availible.
*/
SourceMapConsumer.prototype.sourceContentFor =
function SourceMapConsumer_sourceContentFor(aSource) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot
&& (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// path_to_url
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.generatedPositionFor =
function SourceMapConsumer_generatedPositionFor(aArgs) {
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
if (this.sourceRoot) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
var mapping = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
};
}
return {
line: null,
column: null
};
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping =
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source;
if (source && sourceRoot) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name
};
}).forEach(aCallback, context);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
``` | /content/code_sandbox/node_modules/source-map/lib/source-map/source-map-consumer.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,879 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var binarySearch = require('../../lib/source-map/binary-search');
function numberCompare(a, b) {
return a - b;
}
exports['test too high'] = function (assert, util) {
var needle = 30;
var haystack = [2,4,6,8,10,12,14,16,18,20];
assert.doesNotThrow(function () {
binarySearch.search(needle, haystack, numberCompare);
});
assert.equal(binarySearch.search(needle, haystack, numberCompare), 20);
};
exports['test too low'] = function (assert, util) {
var needle = 1;
var haystack = [2,4,6,8,10,12,14,16,18,20];
assert.doesNotThrow(function () {
binarySearch.search(needle, haystack, numberCompare);
});
assert.equal(binarySearch.search(needle, haystack, numberCompare), null);
};
exports['test exact search'] = function (assert, util) {
var needle = 4;
var haystack = [2,4,6,8,10,12,14,16,18,20];
assert.equal(binarySearch.search(needle, haystack, numberCompare), 4);
};
exports['test fuzzy search'] = function (assert, util) {
var needle = 19;
var haystack = [2,4,6,8,10,12,14,16,18,20];
assert.equal(binarySearch.search(needle, haystack, numberCompare), 18);
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-binary-search.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 397 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var base64VLQ = require('../../lib/source-map/base64-vlq');
exports['test normal encoding and decoding'] = function (assert, util) {
var result;
for (var i = -255; i < 256; i++) {
result = base64VLQ.decode(base64VLQ.encode(i));
assert.ok(result);
assert.equal(result.value, i);
assert.equal(result.rest, "");
}
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-base64-vlq.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 152 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator;
var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer;
var SourceNode = require('../../lib/source-map/source-node').SourceNode;
var util = require('./util');
exports['test some simple stuff'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'foo.js',
sourceRoot: '.'
});
assert.ok(true);
};
exports['test JSON serialization'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'foo.js',
sourceRoot: '.'
});
assert.equal(map.toString(), JSON.stringify(map));
};
exports['test adding mappings (case 1)'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'generated-foo.js',
sourceRoot: '.'
});
assert.doesNotThrow(function () {
map.addMapping({
generated: { line: 1, column: 1 }
});
});
};
exports['test adding mappings (case 2)'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'generated-foo.js',
sourceRoot: '.'
});
assert.doesNotThrow(function () {
map.addMapping({
generated: { line: 1, column: 1 },
source: 'bar.js',
original: { line: 1, column: 1 }
});
});
};
exports['test adding mappings (case 3)'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'generated-foo.js',
sourceRoot: '.'
});
assert.doesNotThrow(function () {
map.addMapping({
generated: { line: 1, column: 1 },
source: 'bar.js',
original: { line: 1, column: 1 },
name: 'someToken'
});
});
};
exports['test adding mappings (invalid)'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'generated-foo.js',
sourceRoot: '.'
});
// Not enough info.
assert.throws(function () {
map.addMapping({});
});
// Original file position, but no source.
assert.throws(function () {
map.addMapping({
generated: { line: 1, column: 1 },
original: { line: 1, column: 1 }
});
});
};
exports['test that the correct mappings are being generated'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'min.js',
sourceRoot: '/the/root'
});
map.addMapping({
generated: { line: 1, column: 1 },
original: { line: 1, column: 1 },
source: 'one.js'
});
map.addMapping({
generated: { line: 1, column: 5 },
original: { line: 1, column: 5 },
source: 'one.js'
});
map.addMapping({
generated: { line: 1, column: 9 },
original: { line: 1, column: 11 },
source: 'one.js'
});
map.addMapping({
generated: { line: 1, column: 18 },
original: { line: 1, column: 21 },
source: 'one.js',
name: 'bar'
});
map.addMapping({
generated: { line: 1, column: 21 },
original: { line: 2, column: 3 },
source: 'one.js'
});
map.addMapping({
generated: { line: 1, column: 28 },
original: { line: 2, column: 10 },
source: 'one.js',
name: 'baz'
});
map.addMapping({
generated: { line: 1, column: 32 },
original: { line: 2, column: 14 },
source: 'one.js',
name: 'bar'
});
map.addMapping({
generated: { line: 2, column: 1 },
original: { line: 1, column: 1 },
source: 'two.js'
});
map.addMapping({
generated: { line: 2, column: 5 },
original: { line: 1, column: 5 },
source: 'two.js'
});
map.addMapping({
generated: { line: 2, column: 9 },
original: { line: 1, column: 11 },
source: 'two.js'
});
map.addMapping({
generated: { line: 2, column: 18 },
original: { line: 1, column: 21 },
source: 'two.js',
name: 'n'
});
map.addMapping({
generated: { line: 2, column: 21 },
original: { line: 2, column: 3 },
source: 'two.js'
});
map.addMapping({
generated: { line: 2, column: 28 },
original: { line: 2, column: 10 },
source: 'two.js',
name: 'n'
});
map = JSON.parse(map.toString());
util.assertEqualMaps(assert, map, util.testMap);
};
exports['test that source content can be set'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'min.js',
sourceRoot: '/the/root'
});
map.addMapping({
generated: { line: 1, column: 1 },
original: { line: 1, column: 1 },
source: 'one.js'
});
map.addMapping({
generated: { line: 2, column: 1 },
original: { line: 1, column: 1 },
source: 'two.js'
});
map.setSourceContent('one.js', 'one file content');
map = JSON.parse(map.toString());
assert.equal(map.sources[0], 'one.js');
assert.equal(map.sources[1], 'two.js');
assert.equal(map.sourcesContent[0], 'one file content');
assert.equal(map.sourcesContent[1], null);
};
exports['test .fromSourceMap'] = function (assert, util) {
var map = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(util.testMap));
util.assertEqualMaps(assert, map.toJSON(), util.testMap);
};
exports['test .fromSourceMap with sourcesContent'] = function (assert, util) {
var map = SourceMapGenerator.fromSourceMap(
new SourceMapConsumer(util.testMapWithSourcesContent));
util.assertEqualMaps(assert, map.toJSON(), util.testMapWithSourcesContent);
};
exports['test applySourceMap'] = function (assert, util) {
var node = new SourceNode(null, null, null, [
new SourceNode(2, 0, 'fileX', 'lineX2\n'),
'genA1\n',
new SourceNode(2, 0, 'fileY', 'lineY2\n'),
'genA2\n',
new SourceNode(1, 0, 'fileX', 'lineX1\n'),
'genA3\n',
new SourceNode(1, 0, 'fileY', 'lineY1\n')
]);
var mapStep1 = node.toStringWithSourceMap({
file: 'fileA'
}).map;
mapStep1.setSourceContent('fileX', 'lineX1\nlineX2\n');
mapStep1 = mapStep1.toJSON();
node = new SourceNode(null, null, null, [
'gen1\n',
new SourceNode(1, 0, 'fileA', 'lineA1\n'),
new SourceNode(2, 0, 'fileA', 'lineA2\n'),
new SourceNode(3, 0, 'fileA', 'lineA3\n'),
new SourceNode(4, 0, 'fileA', 'lineA4\n'),
new SourceNode(1, 0, 'fileB', 'lineB1\n'),
new SourceNode(2, 0, 'fileB', 'lineB2\n'),
'gen2\n'
]);
var mapStep2 = node.toStringWithSourceMap({
file: 'fileGen'
}).map;
mapStep2.setSourceContent('fileB', 'lineB1\nlineB2\n');
mapStep2 = mapStep2.toJSON();
node = new SourceNode(null, null, null, [
'gen1\n',
new SourceNode(2, 0, 'fileX', 'lineA1\n'),
new SourceNode(2, 0, 'fileA', 'lineA2\n'),
new SourceNode(2, 0, 'fileY', 'lineA3\n'),
new SourceNode(4, 0, 'fileA', 'lineA4\n'),
new SourceNode(1, 0, 'fileB', 'lineB1\n'),
new SourceNode(2, 0, 'fileB', 'lineB2\n'),
'gen2\n'
]);
var expectedMap = node.toStringWithSourceMap({
file: 'fileGen'
}).map;
expectedMap.setSourceContent('fileX', 'lineX1\nlineX2\n');
expectedMap.setSourceContent('fileB', 'lineB1\nlineB2\n');
expectedMap = expectedMap.toJSON();
// apply source map "mapStep1" to "mapStep2"
var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(mapStep2));
generator.applySourceMap(new SourceMapConsumer(mapStep1));
var actualMap = generator.toJSON();
util.assertEqualMaps(assert, actualMap, expectedMap);
};
exports['test sorting with duplicate generated mappings'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'test.js'
});
map.addMapping({
generated: { line: 3, column: 0 },
original: { line: 2, column: 0 },
source: 'a.js'
});
map.addMapping({
generated: { line: 2, column: 0 }
});
map.addMapping({
generated: { line: 2, column: 0 }
});
map.addMapping({
generated: { line: 1, column: 0 },
original: { line: 1, column: 0 },
source: 'a.js'
});
util.assertEqualMaps(assert, map.toJSON(), {
version: 3,
file: 'test.js',
sources: ['a.js'],
names: [],
mappings: 'AAAA;A;AACA'
});
};
exports['test ignore duplicate mappings.'] = function (assert, util) {
var init = { file: 'min.js', sourceRoot: '/the/root' };
var map1, map2;
// null original source location
var nullMapping1 = {
generated: { line: 1, column: 0 }
};
var nullMapping2 = {
generated: { line: 2, column: 2 }
};
map1 = new SourceMapGenerator(init);
map2 = new SourceMapGenerator(init);
map1.addMapping(nullMapping1);
map1.addMapping(nullMapping1);
map2.addMapping(nullMapping1);
util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON());
map1.addMapping(nullMapping2);
map1.addMapping(nullMapping1);
map2.addMapping(nullMapping2);
util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON());
// original source location
var srcMapping1 = {
generated: { line: 1, column: 0 },
original: { line: 11, column: 0 },
source: 'srcMapping1.js'
};
var srcMapping2 = {
generated: { line: 2, column: 2 },
original: { line: 11, column: 0 },
source: 'srcMapping2.js'
};
map1 = new SourceMapGenerator(init);
map2 = new SourceMapGenerator(init);
map1.addMapping(srcMapping1);
map1.addMapping(srcMapping1);
map2.addMapping(srcMapping1);
util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON());
map1.addMapping(srcMapping2);
map1.addMapping(srcMapping1);
map2.addMapping(srcMapping2);
util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON());
// full original source and name information
var fullMapping1 = {
generated: { line: 1, column: 0 },
original: { line: 11, column: 0 },
source: 'fullMapping1.js',
name: 'fullMapping1'
};
var fullMapping2 = {
generated: { line: 2, column: 2 },
original: { line: 11, column: 0 },
source: 'fullMapping2.js',
name: 'fullMapping2'
};
map1 = new SourceMapGenerator(init);
map2 = new SourceMapGenerator(init);
map1.addMapping(fullMapping1);
map1.addMapping(fullMapping1);
map2.addMapping(fullMapping1);
util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON());
map1.addMapping(fullMapping2);
map1.addMapping(fullMapping1);
map2.addMapping(fullMapping2);
util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON());
};
exports['test github issue #72, check for duplicate names or sources'] = function (assert, util) {
var map = new SourceMapGenerator({
file: 'test.js'
});
map.addMapping({
generated: { line: 1, column: 1 },
original: { line: 2, column: 2 },
source: 'a.js',
name: 'foo'
});
map.addMapping({
generated: { line: 3, column: 3 },
original: { line: 4, column: 4 },
source: 'a.js',
name: 'foo'
});
util.assertEqualMaps(assert, map.toJSON(), {
version: 3,
file: 'test.js',
sources: ['a.js'],
names: ['foo'],
mappings: 'CACEA;;GAEEA'
});
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-source-map-generator.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,278 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var base64 = require('../../lib/source-map/base64');
exports['test out of range encoding'] = function (assert, util) {
assert.throws(function () {
base64.encode(-1);
});
assert.throws(function () {
base64.encode(64);
});
};
exports['test out of range decoding'] = function (assert, util) {
assert.throws(function () {
base64.decode('=');
});
};
exports['test normal encoding and decoding'] = function (assert, util) {
for (var i = 0; i < 64; i++) {
assert.equal(base64.decode(base64.encode(i)), i);
}
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-base64.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 206 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer;
var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator;
exports['test eating our own dog food'] = function (assert, util) {
var smg = new SourceMapGenerator({
file: 'testing.js',
sourceRoot: '/wu/tang'
});
smg.addMapping({
source: 'gza.coffee',
original: { line: 1, column: 0 },
generated: { line: 2, column: 2 }
});
smg.addMapping({
source: 'gza.coffee',
original: { line: 2, column: 0 },
generated: { line: 3, column: 2 }
});
smg.addMapping({
source: 'gza.coffee',
original: { line: 3, column: 0 },
generated: { line: 4, column: 2 }
});
smg.addMapping({
source: 'gza.coffee',
original: { line: 4, column: 0 },
generated: { line: 5, column: 2 }
});
var smc = new SourceMapConsumer(smg.toString());
// Exact
util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 0, null, smc, assert);
util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 0, null, smc, assert);
util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 0, null, smc, assert);
util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 0, null, smc, assert);
// Fuzzy
// Original to generated
util.assertMapping(2, 0, null, null, null, null, smc, assert, true);
util.assertMapping(2, 9, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true);
util.assertMapping(3, 0, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true);
util.assertMapping(3, 9, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true);
util.assertMapping(4, 0, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true);
util.assertMapping(4, 9, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true);
util.assertMapping(5, 0, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true);
util.assertMapping(5, 9, '/wu/tang/gza.coffee', 4, 0, null, smc, assert, true);
// Generated to original
util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 1, null, smc, assert, null, true);
util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 3, null, smc, assert, null, true);
util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 6, null, smc, assert, null, true);
util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 9, null, smc, assert, null, true);
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-dog-fooding.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 893 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var util = require('../../lib/source-map/util');
// This is a test mapping which maps functions from two different files
// (one.js and two.js) to a minified generated source.
//
// Here is one.js:
//
// ONE.foo = function (bar) {
// return baz(bar);
// };
//
// Here is two.js:
//
// TWO.inc = function (n) {
// return n + 1;
// };
//
// And here is the generated code (min.js):
//
// ONE.foo=function(a){return baz(a);};
// TWO.inc=function(a){return a+1;};
exports.testGeneratedCode = " ONE.foo=function(a){return baz(a);};\n"+
" TWO.inc=function(a){return a+1;};";
exports.testMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: '/the/root',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
exports.testMapWithSourcesContent = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourcesContent: [
' ONE.foo = function (bar) {\n' +
' return baz(bar);\n' +
' };',
' TWO.inc = function (n) {\n' +
' return n + 1;\n' +
' };'
],
sourceRoot: '/the/root',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
exports.emptyMap = {
version: 3,
file: 'min.js',
names: [],
sources: [],
mappings: ''
};
function assertMapping(generatedLine, generatedColumn, originalSource,
originalLine, originalColumn, name, map, assert,
dontTestGenerated, dontTestOriginal) {
if (!dontTestOriginal) {
var origMapping = map.originalPositionFor({
line: generatedLine,
column: generatedColumn
});
assert.equal(origMapping.name, name,
'Incorrect name, expected ' + JSON.stringify(name)
+ ', got ' + JSON.stringify(origMapping.name));
assert.equal(origMapping.line, originalLine,
'Incorrect line, expected ' + JSON.stringify(originalLine)
+ ', got ' + JSON.stringify(origMapping.line));
assert.equal(origMapping.column, originalColumn,
'Incorrect column, expected ' + JSON.stringify(originalColumn)
+ ', got ' + JSON.stringify(origMapping.column));
var expectedSource;
if (originalSource && map.sourceRoot && originalSource.indexOf(map.sourceRoot) === 0) {
expectedSource = originalSource;
} else if (originalSource) {
expectedSource = map.sourceRoot
? util.join(map.sourceRoot, originalSource)
: originalSource;
} else {
expectedSource = null;
}
assert.equal(origMapping.source, expectedSource,
'Incorrect source, expected ' + JSON.stringify(expectedSource)
+ ', got ' + JSON.stringify(origMapping.source));
}
if (!dontTestGenerated) {
var genMapping = map.generatedPositionFor({
source: originalSource,
line: originalLine,
column: originalColumn
});
assert.equal(genMapping.line, generatedLine,
'Incorrect line, expected ' + JSON.stringify(generatedLine)
+ ', got ' + JSON.stringify(genMapping.line));
assert.equal(genMapping.column, generatedColumn,
'Incorrect column, expected ' + JSON.stringify(generatedColumn)
+ ', got ' + JSON.stringify(genMapping.column));
}
}
exports.assertMapping = assertMapping;
function assertEqualMaps(assert, actualMap, expectedMap) {
assert.equal(actualMap.version, expectedMap.version, "version mismatch");
assert.equal(actualMap.file, expectedMap.file, "file mismatch");
assert.equal(actualMap.names.length,
expectedMap.names.length,
"names length mismatch: " +
actualMap.names.join(", ") + " != " + expectedMap.names.join(", "));
for (var i = 0; i < actualMap.names.length; i++) {
assert.equal(actualMap.names[i],
expectedMap.names[i],
"names[" + i + "] mismatch: " +
actualMap.names.join(", ") + " != " + expectedMap.names.join(", "));
}
assert.equal(actualMap.sources.length,
expectedMap.sources.length,
"sources length mismatch: " +
actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", "));
for (var i = 0; i < actualMap.sources.length; i++) {
assert.equal(actualMap.sources[i],
expectedMap.sources[i],
"sources[" + i + "] length mismatch: " +
actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", "));
}
assert.equal(actualMap.sourceRoot,
expectedMap.sourceRoot,
"sourceRoot mismatch: " +
actualMap.sourceRoot + " != " + expectedMap.sourceRoot);
assert.equal(actualMap.mappings, expectedMap.mappings,
"mappings mismatch:\nActual: " + actualMap.mappings + "\nExpected: " + expectedMap.mappings);
if (actualMap.sourcesContent) {
assert.equal(actualMap.sourcesContent.length,
expectedMap.sourcesContent.length,
"sourcesContent length mismatch");
for (var i = 0; i < actualMap.sourcesContent.length; i++) {
assert.equal(actualMap.sourcesContent[i],
expectedMap.sourcesContent[i],
"sourcesContent[" + i + "] mismatch");
}
}
}
exports.assertEqualMaps = assertEqualMaps;
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/util.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,375 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var sourceMap;
try {
sourceMap = require('../../lib/source-map');
} catch (e) {
sourceMap = {};
Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);
}
exports['test that the api is properly exposed in the top level'] = function (assert, util) {
assert.equal(typeof sourceMap.SourceMapGenerator, "function");
assert.equal(typeof sourceMap.SourceMapConsumer, "function");
assert.equal(typeof sourceMap.SourceNode, "function");
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-api.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 171 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator;
var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer;
var SourceNode = require('../../lib/source-map/source-node').SourceNode;
exports['test .add()'] = function (assert, util) {
var node = new SourceNode(null, null, null);
// Adding a string works.
node.add('function noop() {}');
// Adding another source node works.
node.add(new SourceNode(null, null, null));
// Adding an array works.
node.add(['function foo() {',
new SourceNode(null, null, null,
'return 10;'),
'}']);
// Adding other stuff doesn't.
assert.throws(function () {
node.add({});
});
assert.throws(function () {
node.add(function () {});
});
};
exports['test .prepend()'] = function (assert, util) {
var node = new SourceNode(null, null, null);
// Prepending a string works.
node.prepend('function noop() {}');
assert.equal(node.children[0], 'function noop() {}');
assert.equal(node.children.length, 1);
// Prepending another source node works.
node.prepend(new SourceNode(null, null, null));
assert.equal(node.children[0], '');
assert.equal(node.children[1], 'function noop() {}');
assert.equal(node.children.length, 2);
// Prepending an array works.
node.prepend(['function foo() {',
new SourceNode(null, null, null,
'return 10;'),
'}']);
assert.equal(node.children[0], 'function foo() {');
assert.equal(node.children[1], 'return 10;');
assert.equal(node.children[2], '}');
assert.equal(node.children[3], '');
assert.equal(node.children[4], 'function noop() {}');
assert.equal(node.children.length, 5);
// Prepending other stuff doesn't.
assert.throws(function () {
node.prepend({});
});
assert.throws(function () {
node.prepend(function () {});
});
};
exports['test .toString()'] = function (assert, util) {
assert.equal((new SourceNode(null, null, null,
['function foo() {',
new SourceNode(null, null, null, 'return 10;'),
'}'])).toString(),
'function foo() {return 10;}');
};
exports['test .join()'] = function (assert, util) {
assert.equal((new SourceNode(null, null, null,
['a', 'b', 'c', 'd'])).join(', ').toString(),
'a, b, c, d');
};
exports['test .walk()'] = function (assert, util) {
var node = new SourceNode(null, null, null,
['(function () {\n',
' ', new SourceNode(1, 0, 'a.js', ['someCall()']), ';\n',
' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';\n',
'}());']);
var expected = [
{ str: '(function () {\n', source: null, line: null, column: null },
{ str: ' ', source: null, line: null, column: null },
{ str: 'someCall()', source: 'a.js', line: 1, column: 0 },
{ str: ';\n', source: null, line: null, column: null },
{ str: ' ', source: null, line: null, column: null },
{ str: 'if (foo) bar()', source: 'b.js', line: 2, column: 0 },
{ str: ';\n', source: null, line: null, column: null },
{ str: '}());', source: null, line: null, column: null },
];
var i = 0;
node.walk(function (chunk, loc) {
assert.equal(expected[i].str, chunk);
assert.equal(expected[i].source, loc.source);
assert.equal(expected[i].line, loc.line);
assert.equal(expected[i].column, loc.column);
i++;
});
};
exports['test .replaceRight'] = function (assert, util) {
var node;
// Not nested
node = new SourceNode(null, null, null, 'hello world');
node.replaceRight(/world/, 'universe');
assert.equal(node.toString(), 'hello universe');
// Nested
node = new SourceNode(null, null, null,
[new SourceNode(null, null, null, 'hey sexy mama, '),
new SourceNode(null, null, null, 'want to kill all humans?')]);
node.replaceRight(/kill all humans/, 'watch Futurama');
assert.equal(node.toString(), 'hey sexy mama, want to watch Futurama?');
};
exports['test .toStringWithSourceMap()'] = function (assert, util) {
var node = new SourceNode(null, null, null,
['(function () {\n',
' ',
new SourceNode(1, 0, 'a.js', 'someCall', 'originalCall'),
new SourceNode(1, 8, 'a.js', '()'),
';\n',
' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';\n',
'}());']);
var map = node.toStringWithSourceMap({
file: 'foo.js'
}).map;
assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator');
map = new SourceMapConsumer(map.toString());
var actual;
actual = map.originalPositionFor({
line: 1,
column: 4
});
assert.equal(actual.source, null);
assert.equal(actual.line, null);
assert.equal(actual.column, null);
actual = map.originalPositionFor({
line: 2,
column: 2
});
assert.equal(actual.source, 'a.js');
assert.equal(actual.line, 1);
assert.equal(actual.column, 0);
assert.equal(actual.name, 'originalCall');
actual = map.originalPositionFor({
line: 3,
column: 2
});
assert.equal(actual.source, 'b.js');
assert.equal(actual.line, 2);
assert.equal(actual.column, 0);
actual = map.originalPositionFor({
line: 3,
column: 16
});
assert.equal(actual.source, null);
assert.equal(actual.line, null);
assert.equal(actual.column, null);
actual = map.originalPositionFor({
line: 4,
column: 2
});
assert.equal(actual.source, null);
assert.equal(actual.line, null);
assert.equal(actual.column, null);
};
exports['test .fromStringWithSourceMap()'] = function (assert, util) {
var node = SourceNode.fromStringWithSourceMap(
util.testGeneratedCode,
new SourceMapConsumer(util.testMap));
var result = node.toStringWithSourceMap({
file: 'min.js'
});
var map = result.map;
var code = result.code;
assert.equal(code, util.testGeneratedCode);
assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator');
map = map.toJSON();
assert.equal(map.version, util.testMap.version);
assert.equal(map.file, util.testMap.file);
assert.equal(map.mappings, util.testMap.mappings);
};
exports['test .fromStringWithSourceMap() empty map'] = function (assert, util) {
var node = SourceNode.fromStringWithSourceMap(
util.testGeneratedCode,
new SourceMapConsumer(util.emptyMap));
var result = node.toStringWithSourceMap({
file: 'min.js'
});
var map = result.map;
var code = result.code;
assert.equal(code, util.testGeneratedCode);
assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator');
map = map.toJSON();
assert.equal(map.version, util.emptyMap.version);
assert.equal(map.file, util.emptyMap.file);
assert.equal(map.mappings.length, util.emptyMap.mappings.length);
assert.equal(map.mappings, util.emptyMap.mappings);
};
exports['test .fromStringWithSourceMap() complex version'] = function (assert, util) {
var input = new SourceNode(null, null, null, [
"(function() {\n",
" var Test = {};\n",
" ", new SourceNode(1, 0, "a.js", "Test.A = { value: 1234 };\n"),
" ", new SourceNode(2, 0, "a.js", "Test.A.x = 'xyz';"), "\n",
"}());\n",
"/* Generated Source */"]);
input = input.toStringWithSourceMap({
file: 'foo.js'
});
var node = SourceNode.fromStringWithSourceMap(
input.code,
new SourceMapConsumer(input.map.toString()));
var result = node.toStringWithSourceMap({
file: 'foo.js'
});
var map = result.map;
var code = result.code;
assert.equal(code, input.code);
assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator');
map = map.toJSON();
var inputMap = input.map.toJSON();
util.assertEqualMaps(assert, map, inputMap);
};
exports['test .fromStringWithSourceMap() merging duplicate mappings'] = function (assert, util) {
var input = new SourceNode(null, null, null, [
new SourceNode(1, 0, "a.js", "(function"),
new SourceNode(1, 0, "a.js", "() {\n"),
" ",
new SourceNode(1, 0, "a.js", "var Test = "),
new SourceNode(1, 0, "b.js", "{};\n"),
new SourceNode(2, 0, "b.js", "Test"),
new SourceNode(2, 0, "b.js", ".A", "A"),
new SourceNode(2, 20, "b.js", " = { value: 1234 };\n", "A"),
"}());\n",
"/* Generated Source */"
]);
input = input.toStringWithSourceMap({
file: 'foo.js'
});
var correctMap = new SourceMapGenerator({
file: 'foo.js'
});
correctMap.addMapping({
generated: { line: 1, column: 0 },
source: 'a.js',
original: { line: 1, column: 0 }
});
correctMap.addMapping({
generated: { line: 2, column: 0 }
});
correctMap.addMapping({
generated: { line: 2, column: 2 },
source: 'a.js',
original: { line: 1, column: 0 }
});
correctMap.addMapping({
generated: { line: 2, column: 13 },
source: 'b.js',
original: { line: 1, column: 0 }
});
correctMap.addMapping({
generated: { line: 3, column: 0 },
source: 'b.js',
original: { line: 2, column: 0 }
});
correctMap.addMapping({
generated: { line: 3, column: 4 },
source: 'b.js',
name: 'A',
original: { line: 2, column: 0 }
});
correctMap.addMapping({
generated: { line: 3, column: 6 },
source: 'b.js',
name: 'A',
original: { line: 2, column: 20 }
});
correctMap.addMapping({
generated: { line: 4, column: 0 }
});
var inputMap = input.map.toJSON();
correctMap = correctMap.toJSON();
util.assertEqualMaps(assert, correctMap, inputMap);
};
exports['test setSourceContent with toStringWithSourceMap'] = function (assert, util) {
var aNode = new SourceNode(1, 1, 'a.js', 'a');
aNode.setSourceContent('a.js', 'someContent');
var node = new SourceNode(null, null, null,
['(function () {\n',
' ', aNode,
' ', new SourceNode(1, 1, 'b.js', 'b'),
'}());']);
node.setSourceContent('b.js', 'otherContent');
var map = node.toStringWithSourceMap({
file: 'foo.js'
}).map;
assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator');
map = new SourceMapConsumer(map.toString());
assert.equal(map.sources.length, 2);
assert.equal(map.sources[0], 'a.js');
assert.equal(map.sources[1], 'b.js');
assert.equal(map.sourcesContent.length, 2);
assert.equal(map.sourcesContent[0], 'someContent');
assert.equal(map.sourcesContent[1], 'otherContent');
};
exports['test walkSourceContents'] = function (assert, util) {
var aNode = new SourceNode(1, 1, 'a.js', 'a');
aNode.setSourceContent('a.js', 'someContent');
var node = new SourceNode(null, null, null,
['(function () {\n',
' ', aNode,
' ', new SourceNode(1, 1, 'b.js', 'b'),
'}());']);
node.setSourceContent('b.js', 'otherContent');
var results = [];
node.walkSourceContents(function (sourceFile, sourceContent) {
results.push([sourceFile, sourceContent]);
});
assert.equal(results.length, 2);
assert.equal(results[0][0], 'a.js');
assert.equal(results[0][1], 'someContent');
assert.equal(results[1][0], 'b.js');
assert.equal(results[1][1], 'otherContent');
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-source-node.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,175 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
/*
* WARNING!
*
* Do not edit this file directly, it is built from the sources at
* path_to_url
*/
Components.utils.import('resource://gre/modules/devtools/Require.jsm');
Components.utils.import('resource://gre/modules/devtools/SourceMap.jsm');
this.EXPORTED_SYMBOLS = [ "define", "runSourceMapTests" ];
``` | /content/code_sandbox/node_modules/source-map/build/prefix-utils.jsm | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 99 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
///////////////////////////////////////////////////////////////////////////////
this.sourceMap = {
SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer,
SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator,
SourceNode: require('source-map/source-node').SourceNode
};
``` | /content/code_sandbox/node_modules/source-map/build/suffix-browser.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 73 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
/**
* Define a module along with a payload.
* @param {string} moduleName Name for the payload
* @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec
* @param {function} payload Function with (require, exports, module) params
*/
function define(moduleName, deps, payload) {
if (typeof moduleName != "string") {
throw new TypeError('Expected string, got: ' + moduleName);
}
if (arguments.length == 2) {
payload = deps;
}
if (moduleName in define.modules) {
throw new Error("Module already defined: " + moduleName);
}
define.modules[moduleName] = payload;
};
/**
* The global store of un-instantiated modules
*/
define.modules = {};
/**
* We invoke require() in the context of a Domain so we can have multiple
* sets of modules running separate from each other.
* This contrasts with JSMs which are singletons, Domains allows us to
* optionally load a CommonJS module twice with separate data each time.
* Perhaps you want 2 command lines with a different set of commands in each,
* for example.
*/
function Domain() {
this.modules = {};
this._currentModule = null;
}
(function () {
/**
* Lookup module names and resolve them by calling the definition function if
* needed.
* There are 2 ways to call this, either with an array of dependencies and a
* callback to call when the dependencies are found (which can happen
* asynchronously in an in-page context) or with a single string an no callback
* where the dependency is resolved synchronously and returned.
* The API is designed to be compatible with the CommonJS AMD spec and
* RequireJS.
* @param {string[]|string} deps A name, or names for the payload
* @param {function|undefined} callback Function to call when the dependencies
* are resolved
* @return {undefined|object} The module required or undefined for
* array/callback method
*/
Domain.prototype.require = function(deps, callback) {
if (Array.isArray(deps)) {
var params = deps.map(function(dep) {
return this.lookup(dep);
}, this);
if (callback) {
callback.apply(null, params);
}
return undefined;
}
else {
return this.lookup(deps);
}
};
function normalize(path) {
var bits = path.split('/');
var i = 1;
while (i < bits.length) {
if (bits[i] === '..') {
bits.splice(i-1, 1);
} else if (bits[i] === '.') {
bits.splice(i, 1);
} else {
i++;
}
}
return bits.join('/');
}
function join(a, b) {
a = a.trim();
b = b.trim();
if (/^\//.test(b)) {
return b;
} else {
return a.replace(/\/*$/, '/') + b;
}
}
function dirname(path) {
var bits = path.split('/');
bits.pop();
return bits.join('/');
}
/**
* Lookup module names and resolve them by calling the definition function if
* needed.
* @param {string} moduleName A name for the payload to lookup
* @return {object} The module specified by aModuleName or null if not found.
*/
Domain.prototype.lookup = function(moduleName) {
if (/^\./.test(moduleName)) {
moduleName = normalize(join(dirname(this._currentModule), moduleName));
}
if (moduleName in this.modules) {
var module = this.modules[moduleName];
return module;
}
if (!(moduleName in define.modules)) {
throw new Error("Module not defined: " + moduleName);
}
var module = define.modules[moduleName];
if (typeof module == "function") {
var exports = {};
var previousModule = this._currentModule;
this._currentModule = moduleName;
module(this.require.bind(this), exports, { id: moduleName, uri: "" });
this._currentModule = previousModule;
module = exports;
}
// cache the resulting module object for next time
this.modules[moduleName] = module;
return module;
};
}());
define.Domain = Domain;
define.globalDomain = new Domain();
var require = define.globalDomain.require.bind(define.globalDomain);
``` | /content/code_sandbox/node_modules/source-map/build/mini-require.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 973 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
///////////////////////////////////////////////////////////////////////////////
this.SourceMapConsumer = require('source-map/source-map-consumer').SourceMapConsumer;
this.SourceMapGenerator = require('source-map/source-map-generator').SourceMapGenerator;
this.SourceNode = require('source-map/source-node').SourceNode;
``` | /content/code_sandbox/node_modules/source-map/build/suffix-source-map.jsm | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 67 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
/*
* WARNING!
*
* Do not edit this file directly, it is built from the sources at
* path_to_url
*/
///////////////////////////////////////////////////////////////////////////////
this.EXPORTED_SYMBOLS = [ "SourceMapConsumer", "SourceMapGenerator", "SourceNode" ];
Components.utils.import('resource://gre/modules/devtools/Require.jsm');
``` | /content/code_sandbox/node_modules/source-map/build/prefix-source-map.jsm | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 91 |
```javascript
function run_test() {
runSourceMapTests('{THIS_MODULE}', do_throw);
}
``` | /content/code_sandbox/node_modules/source-map/build/test-suffix.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 19 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
function runSourceMapTests(modName, do_throw) {
let mod = require(modName);
let assert = require('test/source-map/assert');
let util = require('test/source-map/util');
assert.init(do_throw);
for (let k in mod) {
if (/^test/.test(k)) {
mod[k](assert, util);
}
}
}
this.runSourceMapTests = runSourceMapTests;
``` | /content/code_sandbox/node_modules/source-map/build/suffix-utils.jsm | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 114 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer;
var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator;
exports['test that we can instantiate with a string or an objects'] = function (assert, util) {
assert.doesNotThrow(function () {
var map = new SourceMapConsumer(util.testMap);
});
assert.doesNotThrow(function () {
var map = new SourceMapConsumer(JSON.stringify(util.testMap));
});
};
exports['test that the `sources` field has the original sources'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMap);
var sources = map.sources;
assert.equal(sources[0], '/the/root/one.js');
assert.equal(sources[1], '/the/root/two.js');
assert.equal(sources.length, 2);
};
exports['test that the source root is reflected in a mapping\'s source field'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMap);
var mapping;
mapping = map.originalPositionFor({
line: 2,
column: 1
});
assert.equal(mapping.source, '/the/root/two.js');
mapping = map.originalPositionFor({
line: 1,
column: 1
});
assert.equal(mapping.source, '/the/root/one.js');
};
exports['test mapping tokens back exactly'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMap);
util.assertMapping(1, 1, '/the/root/one.js', 1, 1, null, map, assert);
util.assertMapping(1, 5, '/the/root/one.js', 1, 5, null, map, assert);
util.assertMapping(1, 9, '/the/root/one.js', 1, 11, null, map, assert);
util.assertMapping(1, 18, '/the/root/one.js', 1, 21, 'bar', map, assert);
util.assertMapping(1, 21, '/the/root/one.js', 2, 3, null, map, assert);
util.assertMapping(1, 28, '/the/root/one.js', 2, 10, 'baz', map, assert);
util.assertMapping(1, 32, '/the/root/one.js', 2, 14, 'bar', map, assert);
util.assertMapping(2, 1, '/the/root/two.js', 1, 1, null, map, assert);
util.assertMapping(2, 5, '/the/root/two.js', 1, 5, null, map, assert);
util.assertMapping(2, 9, '/the/root/two.js', 1, 11, null, map, assert);
util.assertMapping(2, 18, '/the/root/two.js', 1, 21, 'n', map, assert);
util.assertMapping(2, 21, '/the/root/two.js', 2, 3, null, map, assert);
util.assertMapping(2, 28, '/the/root/two.js', 2, 10, 'n', map, assert);
};
exports['test mapping tokens fuzzy'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMap);
// Finding original positions
util.assertMapping(1, 20, '/the/root/one.js', 1, 21, 'bar', map, assert, true);
util.assertMapping(1, 30, '/the/root/one.js', 2, 10, 'baz', map, assert, true);
util.assertMapping(2, 12, '/the/root/two.js', 1, 11, null, map, assert, true);
// Finding generated positions
util.assertMapping(1, 18, '/the/root/one.js', 1, 22, 'bar', map, assert, null, true);
util.assertMapping(1, 28, '/the/root/one.js', 2, 13, 'baz', map, assert, null, true);
util.assertMapping(2, 9, '/the/root/two.js', 1, 16, null, map, assert, null, true);
};
exports['test creating source map consumers with )]}\' prefix'] = function (assert, util) {
assert.doesNotThrow(function () {
var map = new SourceMapConsumer(")]}'" + JSON.stringify(util.testMap));
});
};
exports['test eachMapping'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMap);
var previousLine = -Infinity;
var previousColumn = -Infinity;
map.eachMapping(function (mapping) {
assert.ok(mapping.generatedLine >= previousLine);
if (mapping.source) {
assert.equal(mapping.source.indexOf(util.testMap.sourceRoot), 0);
}
if (mapping.generatedLine === previousLine) {
assert.ok(mapping.generatedColumn >= previousColumn);
previousColumn = mapping.generatedColumn;
}
else {
previousLine = mapping.generatedLine;
previousColumn = -Infinity;
}
});
};
exports['test iterating over mappings in a different order'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMap);
var previousLine = -Infinity;
var previousColumn = -Infinity;
var previousSource = "";
map.eachMapping(function (mapping) {
assert.ok(mapping.source >= previousSource);
if (mapping.source === previousSource) {
assert.ok(mapping.originalLine >= previousLine);
if (mapping.originalLine === previousLine) {
assert.ok(mapping.originalColumn >= previousColumn);
previousColumn = mapping.originalColumn;
}
else {
previousLine = mapping.originalLine;
previousColumn = -Infinity;
}
}
else {
previousSource = mapping.source;
previousLine = -Infinity;
previousColumn = -Infinity;
}
}, null, SourceMapConsumer.ORIGINAL_ORDER);
};
exports['test that we can set the context for `this` in eachMapping'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMap);
var context = {};
map.eachMapping(function () {
assert.equal(this, context);
}, context);
};
exports['test that the `sourcesContent` field has the original sources'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMapWithSourcesContent);
var sourcesContent = map.sourcesContent;
assert.equal(sourcesContent[0], ' ONE.foo = function (bar) {\n return baz(bar);\n };');
assert.equal(sourcesContent[1], ' TWO.inc = function (n) {\n return n + 1;\n };');
assert.equal(sourcesContent.length, 2);
};
exports['test that we can get the original sources for the sources'] = function (assert, util) {
var map = new SourceMapConsumer(util.testMapWithSourcesContent);
var sources = map.sources;
assert.equal(map.sourceContentFor(sources[0]), ' ONE.foo = function (bar) {\n return baz(bar);\n };');
assert.equal(map.sourceContentFor(sources[1]), ' TWO.inc = function (n) {\n return n + 1;\n };');
assert.equal(map.sourceContentFor("one.js"), ' ONE.foo = function (bar) {\n return baz(bar);\n };');
assert.equal(map.sourceContentFor("two.js"), ' TWO.inc = function (n) {\n return n + 1;\n };');
assert.throws(function () {
map.sourceContentFor("");
}, Error);
assert.throws(function () {
map.sourceContentFor("/the/root/three.js");
}, Error);
assert.throws(function () {
map.sourceContentFor("three.js");
}, Error);
};
exports['test sourceRoot + generatedPositionFor'] = function (assert, util) {
var map = new SourceMapGenerator({
sourceRoot: 'foo/bar',
file: 'baz.js'
});
map.addMapping({
original: { line: 1, column: 1 },
generated: { line: 2, column: 2 },
source: 'bang.coffee'
});
map.addMapping({
original: { line: 5, column: 5 },
generated: { line: 6, column: 6 },
source: 'bang.coffee'
});
map = new SourceMapConsumer(map.toString());
// Should handle without sourceRoot.
var pos = map.generatedPositionFor({
line: 1,
column: 1,
source: 'bang.coffee'
});
assert.equal(pos.line, 2);
assert.equal(pos.column, 2);
// Should handle with sourceRoot.
var pos = map.generatedPositionFor({
line: 1,
column: 1,
source: 'foo/bar/bang.coffee'
});
assert.equal(pos.line, 2);
assert.equal(pos.column, 2);
};
exports['test sourceRoot + originalPositionFor'] = function (assert, util) {
var map = new SourceMapGenerator({
sourceRoot: 'foo/bar',
file: 'baz.js'
});
map.addMapping({
original: { line: 1, column: 1 },
generated: { line: 2, column: 2 },
source: 'bang.coffee'
});
map = new SourceMapConsumer(map.toString());
var pos = map.originalPositionFor({
line: 2,
column: 2,
});
// Should always have the prepended source root
assert.equal(pos.source, 'foo/bar/bang.coffee');
assert.equal(pos.line, 1);
assert.equal(pos.column, 1);
};
exports['test github issue #56'] = function (assert, util) {
var map = new SourceMapGenerator({
sourceRoot: 'path_to_url
file: 'www.example.com/foo.js'
});
map.addMapping({
original: { line: 1, column: 1 },
generated: { line: 2, column: 2 },
source: 'www.example.com/original.js'
});
map = new SourceMapConsumer(map.toString());
var sources = map.sources;
assert.equal(sources.length, 1);
assert.equal(sources[0], 'path_to_url
};
exports['test github issue #43'] = function (assert, util) {
var map = new SourceMapGenerator({
sourceRoot: 'path_to_url
file: 'foo.js'
});
map.addMapping({
original: { line: 1, column: 1 },
generated: { line: 2, column: 2 },
source: 'path_to_url
});
map = new SourceMapConsumer(map.toString());
var sources = map.sources;
assert.equal(sources.length, 1,
'Should only be one source.');
assert.equal(sources[0], 'path_to_url
'Should not be joined with the sourceRoot.');
};
exports['test absolute path, but same host sources'] = function (assert, util) {
var map = new SourceMapGenerator({
sourceRoot: 'path_to_url
file: 'foo.js'
});
map.addMapping({
original: { line: 1, column: 1 },
generated: { line: 2, column: 2 },
source: '/original.js'
});
map = new SourceMapConsumer(map.toString());
var sources = map.sources;
assert.equal(sources.length, 1,
'Should only be one source.');
assert.equal(sources[0], 'path_to_url
'Source should be relative the host of the source root.');
};
exports['test github issue #64'] = function (assert, util) {
var map = new SourceMapConsumer({
"version": 3,
"file": "foo.js",
"sourceRoot": "path_to_url",
"sources": ["/a"],
"names": [],
"mappings": "AACA",
"sourcesContent": ["foo"]
});
assert.equal(map.sourceContentFor("a"), "foo");
assert.equal(map.sourceContentFor("/a"), "foo");
};
exports['test bug 885597'] = function (assert, util) {
var map = new SourceMapConsumer({
"version": 3,
"file": "foo.js",
"sourceRoot": "file:///Users/AlGore/Invented/The/Internet/",
"sources": ["/a"],
"names": [],
"mappings": "AACA",
"sourcesContent": ["foo"]
});
var s = map.sources[0];
assert.equal(map.sourceContentFor(s), "foo");
};
exports['test github issue #72, duplicate sources'] = function (assert, util) {
var map = new SourceMapConsumer({
"version": 3,
"file": "foo.js",
"sources": ["source1.js", "source1.js", "source3.js"],
"names": [],
"mappings": ";EAAC;;IAEE;;MEEE",
"sourceRoot": "path_to_url"
});
var pos = map.originalPositionFor({
line: 2,
column: 2
});
assert.equal(pos.source, 'path_to_url
assert.equal(pos.line, 1);
assert.equal(pos.column, 1);
var pos = map.originalPositionFor({
line: 4,
column: 4
});
assert.equal(pos.source, 'path_to_url
assert.equal(pos.line, 3);
assert.equal(pos.column, 3);
var pos = map.originalPositionFor({
line: 6,
column: 6
});
assert.equal(pos.source, 'path_to_url
assert.equal(pos.line, 5);
assert.equal(pos.column, 5);
};
exports['test github issue #72, duplicate names'] = function (assert, util) {
var map = new SourceMapConsumer({
"version": 3,
"file": "foo.js",
"sources": ["source.js"],
"names": ["name1", "name1", "name3"],
"mappings": ";EAACA;;IAEEA;;MAEEE",
"sourceRoot": "path_to_url"
});
var pos = map.originalPositionFor({
line: 2,
column: 2
});
assert.equal(pos.name, 'name1');
assert.equal(pos.line, 1);
assert.equal(pos.column, 1);
var pos = map.originalPositionFor({
line: 4,
column: 4
});
assert.equal(pos.name, 'name1');
assert.equal(pos.line, 3);
assert.equal(pos.column, 3);
var pos = map.originalPositionFor({
line: 6,
column: 6
});
assert.equal(pos.name, 'name3');
assert.equal(pos.line, 5);
assert.equal(pos.column, 5);
};
exports['test SourceMapConsumer.fromSourceMap'] = function (assert, util) {
var smg = new SourceMapGenerator({
sourceRoot: 'path_to_url
file: 'foo.js'
});
smg.addMapping({
original: { line: 1, column: 1 },
generated: { line: 2, column: 2 },
source: 'bar.js'
});
smg.addMapping({
original: { line: 2, column: 2 },
generated: { line: 4, column: 4 },
source: 'baz.js',
name: 'dirtMcGirt'
});
smg.setSourceContent('baz.js', 'baz.js content');
var smc = SourceMapConsumer.fromSourceMap(smg);
assert.equal(smc.file, 'foo.js');
assert.equal(smc.sourceRoot, 'path_to_url
assert.equal(smc.sources.length, 2);
assert.equal(smc.sources[0], 'path_to_url
assert.equal(smc.sources[1], 'path_to_url
assert.equal(smc.sourceContentFor('baz.js'), 'baz.js content');
var pos = smc.originalPositionFor({
line: 2,
column: 2
});
assert.equal(pos.line, 1);
assert.equal(pos.column, 1);
assert.equal(pos.source, 'path_to_url
assert.equal(pos.name, null);
pos = smc.generatedPositionFor({
line: 1,
column: 1,
source: 'path_to_url
});
assert.equal(pos.line, 2);
assert.equal(pos.column, 2);
pos = smc.originalPositionFor({
line: 4,
column: 4
});
assert.equal(pos.line, 2);
assert.equal(pos.column, 2);
assert.equal(pos.source, 'path_to_url
assert.equal(pos.name, 'dirtMcGirt');
pos = smc.generatedPositionFor({
line: 2,
column: 2,
source: 'path_to_url
});
assert.equal(pos.line, 4);
assert.equal(pos.column, 4);
};
});
``` | /content/code_sandbox/node_modules/source-map/test/source-map/test-source-map-consumer.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,875 |
```javascript
/*
* WARNING!
*
* Do not edit this file directly, it is built from the sources at
* path_to_url
*/
Components.utils.import('resource://test/Utils.jsm');
``` | /content/code_sandbox/node_modules/source-map/build/test-prefix.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 40 |
```javascript
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* path_to_url
*/
define('test/source-map/assert', ['exports'], function (exports) {
let do_throw = function (msg) {
throw new Error(msg);
};
exports.init = function (throw_fn) {
do_throw = throw_fn;
};
exports.doesNotThrow = function (fn) {
try {
fn();
}
catch (e) {
do_throw(e.message);
}
};
exports.equal = function (actual, expected, msg) {
msg = msg || String(actual) + ' != ' + String(expected);
if (actual != expected) {
do_throw(msg);
}
};
exports.ok = function (val, msg) {
msg = msg || String(val) + ' is falsey';
if (!Boolean(val)) {
do_throw(msg);
}
};
exports.strictEqual = function (actual, expected, msg) {
msg = msg || String(actual) + ' !== ' + String(expected);
if (actual !== expected) {
do_throw(msg);
}
};
exports.throws = function (fn) {
try {
fn();
do_throw('Expected an error to be thrown, but it wasn\'t.');
}
catch (e) {
}
};
});
``` | /content/code_sandbox/node_modules/source-map/build/assert-shim.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 290 |
```javascript
'use strict';
if (!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = { nextTick: nextTick };
} else {
module.exports = process
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
``` | /content/code_sandbox/node_modules/process-nextick-args/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 291 |
```javascript
'use strict'
// A linked list to keep track of recently-used-ness
const Yallist = require('yallist')
const MAX = Symbol('max')
const LENGTH = Symbol('length')
const LENGTH_CALCULATOR = Symbol('lengthCalculator')
const ALLOW_STALE = Symbol('allowStale')
const MAX_AGE = Symbol('maxAge')
const DISPOSE = Symbol('dispose')
const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')
const LRU_LIST = Symbol('lruList')
const CACHE = Symbol('cache')
const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')
const naiveLength = () => 1
// lruList is a yallist where the head is the youngest
// item, and the tail is the oldest. the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node. This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
class LRUCache {
constructor (options) {
if (typeof options === 'number')
options = { max: options }
if (!options)
options = {}
if (options.max && (typeof options.max !== 'number' || options.max < 0))
throw new TypeError('max must be a non-negative number')
// Kind of weird to have a default max of Infinity, but oh well.
const max = this[MAX] = options.max || Infinity
const lc = options.length || naiveLength
this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc
this[ALLOW_STALE] = options.stale || false
if (options.maxAge && typeof options.maxAge !== 'number')
throw new TypeError('maxAge must be a number')
this[MAX_AGE] = options.maxAge || 0
this[DISPOSE] = options.dispose
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false
this.reset()
}
// resize the cache when the max changes.
set max (mL) {
if (typeof mL !== 'number' || mL < 0)
throw new TypeError('max must be a non-negative number')
this[MAX] = mL || Infinity
trim(this)
}
get max () {
return this[MAX]
}
set allowStale (allowStale) {
this[ALLOW_STALE] = !!allowStale
}
get allowStale () {
return this[ALLOW_STALE]
}
set maxAge (mA) {
if (typeof mA !== 'number')
throw new TypeError('maxAge must be a non-negative number')
this[MAX_AGE] = mA
trim(this)
}
get maxAge () {
return this[MAX_AGE]
}
// resize the cache when the lengthCalculator changes.
set lengthCalculator (lC) {
if (typeof lC !== 'function')
lC = naiveLength
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC
this[LENGTH] = 0
this[LRU_LIST].forEach(hit => {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
this[LENGTH] += hit.length
})
}
trim(this)
}
get lengthCalculator () { return this[LENGTH_CALCULATOR] }
get length () { return this[LENGTH] }
get itemCount () { return this[LRU_LIST].length }
rforEach (fn, thisp) {
thisp = thisp || this
for (let walker = this[LRU_LIST].tail; walker !== null;) {
const prev = walker.prev
forEachStep(this, fn, walker, thisp)
walker = prev
}
}
forEach (fn, thisp) {
thisp = thisp || this
for (let walker = this[LRU_LIST].head; walker !== null;) {
const next = walker.next
forEachStep(this, fn, walker, thisp)
walker = next
}
}
keys () {
return this[LRU_LIST].toArray().map(k => k.key)
}
values () {
return this[LRU_LIST].toArray().map(k => k.value)
}
reset () {
if (this[DISPOSE] &&
this[LRU_LIST] &&
this[LRU_LIST].length) {
this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))
}
this[CACHE] = new Map() // hash of items by key
this[LRU_LIST] = new Yallist() // list of items in order of use recency
this[LENGTH] = 0 // length of items in the list
}
dump () {
return this[LRU_LIST].map(hit =>
isStale(this, hit) ? false : {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
}).toArray().filter(h => h)
}
dumpLru () {
return this[LRU_LIST]
}
set (key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE]
if (maxAge && typeof maxAge !== 'number')
throw new TypeError('maxAge must be a number')
const now = maxAge ? Date.now() : 0
const len = this[LENGTH_CALCULATOR](value, key)
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key))
return false
}
const node = this[CACHE].get(key)
const item = node.value
// dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET])
this[DISPOSE](key, item.value)
}
item.now = now
item.maxAge = maxAge
item.value = value
this[LENGTH] += len - item.length
item.length = len
this.get(key)
trim(this)
return true
}
const hit = new Entry(key, value, len, now, maxAge)
// oversized objects fall out of cache automatically.
if (hit.length > this[MAX]) {
if (this[DISPOSE])
this[DISPOSE](key, value)
return false
}
this[LENGTH] += hit.length
this[LRU_LIST].unshift(hit)
this[CACHE].set(key, this[LRU_LIST].head)
trim(this)
return true
}
has (key) {
if (!this[CACHE].has(key)) return false
const hit = this[CACHE].get(key).value
return !isStale(this, hit)
}
get (key) {
return get(this, key, true)
}
peek (key) {
return get(this, key, false)
}
pop () {
const node = this[LRU_LIST].tail
if (!node)
return null
del(this, node)
return node.value
}
del (key) {
del(this, this[CACHE].get(key))
}
load (arr) {
// reset the cache
this.reset()
const now = Date.now()
// A previous serialized cache has the most recent items first
for (let l = arr.length - 1; l >= 0; l--) {
const hit = arr[l]
const expiresAt = hit.e || 0
if (expiresAt === 0)
// the item was created without expiration in a non aged cache
this.set(hit.k, hit.v)
else {
const maxAge = expiresAt - now
// dont add already expired items
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge)
}
}
}
}
prune () {
this[CACHE].forEach((value, key) => get(this, key, false))
}
}
const get = (self, key, doUse) => {
const node = self[CACHE].get(key)
if (node) {
const hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE])
return undefined
} else {
if (doUse) {
if (self[UPDATE_AGE_ON_GET])
node.value.now = Date.now()
self[LRU_LIST].unshiftNode(node)
}
}
return hit.value
}
}
const isStale = (self, hit) => {
if (!hit || (!hit.maxAge && !self[MAX_AGE]))
return false
const diff = Date.now() - hit.now
return hit.maxAge ? diff > hit.maxAge
: self[MAX_AGE] && (diff > self[MAX_AGE])
}
const trim = self => {
if (self[LENGTH] > self[MAX]) {
for (let walker = self[LRU_LIST].tail;
self[LENGTH] > self[MAX] && walker !== null;) {
// We know that we're about to delete this one, and also
// what the next least recently used key will be, so just
// go ahead and set it now.
const prev = walker.prev
del(self, walker)
walker = prev
}
}
}
const del = (self, node) => {
if (node) {
const hit = node.value
if (self[DISPOSE])
self[DISPOSE](hit.key, hit.value)
self[LENGTH] -= hit.length
self[CACHE].delete(hit.key)
self[LRU_LIST].removeNode(node)
}
}
class Entry {
constructor (key, value, length, now, maxAge) {
this.key = key
this.value = value
this.length = length
this.now = now
this.maxAge = maxAge || 0
}
}
const forEachStep = (self, fn, node, thisp) => {
let hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE])
hit = undefined
}
if (hit)
fn.call(thisp, hit.value, hit.key, self)
}
module.exports = LRUCache
``` | /content/code_sandbox/node_modules/lru-cache/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,342 |
```javascript
'use strict';
require('core-js');
var inspect = require('./');
var test = require('tape');
test('Maps', function (t) {
t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}');
t.end();
});
test('WeakMaps', function (t) {
t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }');
t.end();
});
test('Sets', function (t) {
t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}');
t.end();
});
test('WeakSets', function (t) {
t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }');
t.end();
});
``` | /content/code_sandbox/node_modules/object-inspect/test-core-js.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 175 |
```markdown
# object-inspect <sup>[![Version Badge][2]][1]</sup>
string representations of objects in node and the browser
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
# example
## circular
``` js
var inspect = require('object-inspect');
var obj = { a: 1, b: [3,4] };
obj.c = obj;
console.log(inspect(obj));
```
## dom element
``` js
var inspect = require('object-inspect');
var d = document.createElement('div');
d.setAttribute('id', 'beep');
d.innerHTML = '<b>wooo</b><i>iiiii</i>';
console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ]));
```
output:
```
[ <div id="beep">...</div>, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ]
```
# methods
``` js
var inspect = require('object-inspect')
```
## var s = inspect(obj, opts={})
Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`.
Additional options:
- `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements.
- `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`.
- `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`.
- `indent`: must be "\t", `null`, or a positive integer. Default `null`.
- `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`)
# install
With [npm](path_to_url do:
```
npm install object-inspect
```
# license
MIT
[1]: path_to_url
[2]: path_to_url
[5]: path_to_url
[6]: path_to_url
[7]: path_to_url
[8]: path_to_url#info=devDependencies
[11]: path_to_url
[license-image]: path_to_url
[license-url]: LICENSE
[downloads-image]: path_to_url
[downloads-url]: path_to_url
[codecov-image]: path_to_url
[codecov-url]: path_to_url
[actions-image]: path_to_url
[actions-url]: path_to_url
``` | /content/code_sandbox/node_modules/object-inspect/readme.markdown | markdown | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 672 |
```javascript
module.exports = require('util').inspect;
``` | /content/code_sandbox/node_modules/object-inspect/util.inspect.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 10 |
```javascript
'use strict';
var inspect = require('../');
var Buffer = require('safer-buffer').Buffer;
var holes = ['a', 'b'];
holes[4] = 'e';
holes[6] = 'g';
var obj = {
a: 1,
b: [3, 4, undefined, null],
c: undefined,
d: null,
e: {
regex: /^x/i,
buf: Buffer.from('abc'),
holes: holes
},
now: new Date()
};
obj.self = obj;
console.log(inspect(obj));
``` | /content/code_sandbox/node_modules/object-inspect/example/all.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 123 |
```javascript
'use strict';
var inspect = require('../');
var obj = [1, 2, function f(n) { return n + 5; }, 4];
console.log(inspect(obj));
``` | /content/code_sandbox/node_modules/object-inspect/example/fn.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 40 |
```javascript
'use strict';
/* eslint-env browser */
var inspect = require('../');
var d = document.createElement('div');
d.setAttribute('id', 'beep');
d.innerHTML = '<b>wooo</b><i>iiiii</i>';
console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]));
``` | /content/code_sandbox/node_modules/object-inspect/example/inspect.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 88 |
```javascript
'use strict';
var inspect = require('../');
var obj = { a: 1, b: [3, 4] };
obj.c = obj;
console.log(inspect(obj));
``` | /content/code_sandbox/node_modules/object-inspect/example/circular.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 39 |
```javascript
'use strict';
var inspect = require('../');
var test = require('tape');
test('quoteStyle option', function (t) {
t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value');
t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value');
t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value');
t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value');
t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value');
t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value');
t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value');
t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value');
t.end();
});
``` | /content/code_sandbox/node_modules/object-inspect/test/quoteStyle.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 244 |
```javascript
var test = require('tape');
var forEach = require('for-each');
var inspect = require('../');
test('bad indent options', function (t) {
forEach([
undefined,
true,
false,
-1,
1.2,
Infinity,
-Infinity,
NaN
], function (indent) {
t['throws'](
function () { inspect('', { indent: indent }); },
TypeError,
inspect(indent) + ' is invalid'
);
});
t.end();
});
test('simple object with indent', function (t) {
t.plan(2);
var obj = { a: 1, b: 2 };
var expectedSpaces = [
'{',
' a: 1,',
' b: 2',
'}'
].join('\n');
var expectedTabs = [
'{',
' a: 1,',
' b: 2',
'}'
].join('\n');
t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two');
t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs');
});
test('two deep object with indent', function (t) {
t.plan(2);
var obj = { a: 1, b: { c: 3, d: 4 } };
var expectedSpaces = [
'{',
' a: 1,',
' b: {',
' c: 3,',
' d: 4',
' }',
'}'
].join('\n');
var expectedTabs = [
'{',
' a: 1,',
' b: {',
' c: 3,',
' d: 4',
' }',
'}'
].join('\n');
t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two');
t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs');
});
test('simple array with all single line elements', function (t) {
t.plan(2);
var obj = [1, 2, 3, 'asdf\nsdf'];
var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]';
t.equal(inspect(obj, { indent: 2 }), expected, 'two');
t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs');
});
test('array with complex elements', function (t) {
t.plan(2);
var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf'];
var expectedSpaces = [
'[',
' 1,',
' {',
' a: 1,',
' b: {',
' c: 1',
' }',
' },',
' \'asdf\\nsdf\'',
']'
].join('\n');
var expectedTabs = [
'[',
' 1,',
' {',
' a: 1,',
' b: {',
' c: 1',
' }',
' },',
' \'asdf\\nsdf\'',
']'
].join('\n');
t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two');
t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs');
});
test('values', function (t) {
t.plan(2);
var obj = [{}, [], { 'a-b': 5 }];
var expectedSpaces = [
'[',
' {},',
' [],',
' {',
' \'a-b\': 5',
' }',
']'
].join('\n');
var expectedTabs = [
'[',
' {},',
' [],',
' {',
' \'a-b\': 5',
' }',
']'
].join('\n');
t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two');
t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs');
});
test('Map', { skip: typeof Map !== 'function' }, function (t) {
var map = new Map();
map.set({ a: 1 }, ['b']);
map.set(3, NaN);
var expectedStringSpaces = [
'Map (2) {',
' { a: 1 } => [ \'b\' ],',
' 3 => NaN',
'}'
].join('\n');
var expectedStringTabs = [
'Map (2) {',
' { a: 1 } => [ \'b\' ],',
' 3 => NaN',
'}'
].join('\n');
var expectedStringTabsDoubleQuotes = [
'Map (2) {',
' { a: 1 } => [ "b" ],',
' 3 => NaN',
'}'
].join('\n');
t.equal(
inspect(map, { indent: 2 }),
expectedStringSpaces,
'Map keys are not indented (two)'
);
t.equal(
inspect(map, { indent: '\t' }),
expectedStringTabs,
'Map keys are not indented (tabs)'
);
t.equal(
inspect(map, { indent: '\t', quoteStyle: 'double' }),
expectedStringTabsDoubleQuotes,
'Map keys are not indented (tabs + double quotes)'
);
t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)');
t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)');
var nestedMap = new Map();
nestedMap.set(nestedMap, map);
var expectedNestedSpaces = [
'Map (1) {',
' [Circular] => Map (2) {',
' { a: 1 } => [ \'b\' ],',
' 3 => NaN',
' }',
'}'
].join('\n');
var expectedNestedTabs = [
'Map (1) {',
' [Circular] => Map (2) {',
' { a: 1 } => [ \'b\' ],',
' 3 => NaN',
' }',
'}'
].join('\n');
t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)');
t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)');
t.end();
});
test('Set', { skip: typeof Set !== 'function' }, function (t) {
var set = new Set();
set.add({ a: 1 });
set.add(['b']);
var expectedStringSpaces = [
'Set (2) {',
' {',
' a: 1',
' },',
' [ \'b\' ]',
'}'
].join('\n');
var expectedStringTabs = [
'Set (2) {',
' {',
' a: 1',
' },',
' [ \'b\' ]',
'}'
].join('\n');
t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)');
t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)');
t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)');
t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)');
var nestedSet = new Set();
nestedSet.add(set);
nestedSet.add(nestedSet);
var expectedNestedSpaces = [
'Set (2) {',
' Set (2) {',
' {',
' a: 1',
' },',
' [ \'b\' ]',
' },',
' [Circular]',
'}'
].join('\n');
var expectedNestedTabs = [
'Set (2) {',
' Set (2) {',
' {',
' a: 1',
' },',
' [ \'b\' ]',
' },',
' [Circular]',
'}'
].join('\n');
t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)');
t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)');
t.end();
});
``` | /content/code_sandbox/node_modules/object-inspect/test/indent-option.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 2,040 |
```javascript
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var $match = String.prototype.match;
var $slice = String.prototype.slice;
var $replace = String.prototype.replace;
var $toUpperCase = String.prototype.toUpperCase;
var $toLowerCase = String.prototype.toLowerCase;
var $test = RegExp.prototype.test;
var $concat = Array.prototype.concat;
var $join = Array.prototype.join;
var $arrSlice = Array.prototype.slice;
var $floor = Math.floor;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
// ie, `has-tostringtag/shams
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
? Symbol.toStringTag
: null;
var isEnumerable = Object.prototype.propertyIsEnumerable;
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
[].__proto__ === Array.prototype // eslint-disable-line no-proto
? function (O) {
return O.__proto__; // eslint-disable-line no-proto
}
: null
);
function addNumericSeparator(num, str) {
if (
num === Infinity
|| num === -Infinity
|| num !== num
|| (num && num > -1000 && num < 1000)
|| $test.call(/e/, str)
) {
return str;
}
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
if (typeof num === 'number') {
var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
if (int !== num) {
var intStr = String(int);
var dec = $slice.call(str, intStr.length + 1);
return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
}
}
return $replace.call(str, sepRegex, '$&_');
}
var utilInspect = require('./util.inspect');
var inspectCustom = utilInspect.custom;
var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
module.exports = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
if (
has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
: opts.maxStringLength !== null
)
) {
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
}
var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;
if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
}
if (
has(opts, 'indent')
&& opts.indent !== null
&& opts.indent !== '\t'
&& !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
) {
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
}
if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
}
var numericSeparator = opts.numericSeparator;
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj, opts);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
var str = String(obj);
return numericSeparator ? addNumericSeparator(obj, str) : str;
}
if (typeof obj === 'bigint') {
var bigIntStr = String(obj) + 'n';
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
}
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') { depth = 0; }
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return isArray(obj) ? '[Array]' : '[Object]';
}
var indent = getIndent(opts, depth);
if (typeof seen === 'undefined') {
seen = [];
} else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect(value, from, noIndent) {
if (from) {
seen = $arrSlice.call(seen);
seen.push(from);
}
if (noIndent) {
var newOpts = {
depth: opts.depth
};
if (has(opts, 'quoteStyle')) {
newOpts.quoteStyle = opts.quoteStyle;
}
return inspect_(value, newOpts, depth + 1, seen);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable
var name = nameOf(obj);
var keys = arrObjKeys(obj, inspect);
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
}
if (isSymbol(obj)) {
var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + $toLowerCase.call(String(obj.nodeName));
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
}
s += '>';
if (obj.childNodes && obj.childNodes.length) { s += '...'; }
s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) { return '[]'; }
var xs = arrObjKeys(obj, inspect);
if (indent && !singleLineValues(xs)) {
return '[' + indentedJoin(xs, indent) + ']';
}
return '[ ' + $join.call(xs, ', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {
return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
}
if (parts.length === 0) { return '[' + String(obj) + ']'; }
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
}
if (typeof obj === 'object' && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
return utilInspect(obj, { depth: maxDepth - depth });
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var mapParts = [];
mapForEach.call(obj, function (value, key) {
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
});
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
}
if (isSet(obj)) {
var setParts = [];
setForEach.call(obj, function (value) {
setParts.push(inspect(value, obj));
});
return collectionOf('Set', setSize.call(obj), setParts, indent);
}
if (isWeakMap(obj)) {
return weakCollectionOf('WeakMap');
}
if (isWeakSet(obj)) {
return weakCollectionOf('WeakSet');
}
if (isWeakRef(obj)) {
return weakCollectionOf('WeakRef');
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var ys = arrObjKeys(obj, inspect);
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
var protoTag = obj instanceof Object ? '' : 'null prototype';
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
if (ys.length === 0) { return tag + '{}'; }
if (indent) {
return tag + '{' + indentedJoin(ys, indent) + '}';
}
return tag + '{ ' + $join.call(ys, ', ') + ' }';
}
return String(obj);
};
function wrapQuotes(s, defaultStyle, opts) {
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
return quoteChar + s + quoteChar;
}
function quote(s) {
return $replace.call(String(s), /"/g, '"');
}
function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
function isSymbol(obj) {
if (hasShammedSymbols) {
return obj && typeof obj === 'object' && obj instanceof Symbol;
}
if (typeof obj === 'symbol') {
return true;
}
if (!obj || typeof obj !== 'object' || !symToString) {
return false;
}
try {
symToString.call(obj);
return true;
} catch (e) {}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e) {}
return false;
}
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has(obj, key) {
return hasOwn.call(obj, key);
}
function toStr(obj) {
return objectToString.call(obj);
}
function nameOf(f) {
if (f.name) { return f.name; }
var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
if (m) { return m[1]; }
return null;
}
function indexOf(xs, x) {
if (xs.indexOf) { return xs.indexOf(x); }
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) { return i; }
}
return -1;
}
function isMap(x) {
if (!mapSize || !x || typeof x !== 'object') {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakMap(x) {
if (!weakMapHas || !x || typeof x !== 'object') {
return false;
}
try {
weakMapHas.call(x, weakMapHas);
try {
weakSetHas.call(x, weakSetHas);
} catch (s) {
return true;
}
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakRef(x) {
if (!weakRefDeref || !x || typeof x !== 'object') {
return false;
}
try {
weakRefDeref.call(x);
return true;
} catch (e) {}
return false;
}
function isSet(x) {
if (!setSize || !x || typeof x !== 'object') {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakSet(x) {
if (!weakSetHas || !x || typeof x !== 'object') {
return false;
}
try {
weakSetHas.call(x, weakSetHas);
try {
weakMapHas.call(x, weakMapHas);
} catch (s) {
return true;
}
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement(x) {
if (!x || typeof x !== 'object') { return false; }
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}
function inspectString(str, opts) {
if (str.length > opts.maxStringLength) {
var remaining = str.length - opts.maxStringLength;
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
}
// eslint-disable-next-line no-control-regex
var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s, 'single', opts);
}
function lowbyte(c) {
var n = c.charCodeAt(0);
var x = {
8: 'b',
9: 't',
10: 'n',
12: 'f',
13: 'r'
}[n];
if (x) { return '\\' + x; }
return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
}
function markBoxed(str) {
return 'Object(' + str + ')';
}
function weakCollectionOf(type) {
return type + ' { ? }';
}
function collectionOf(type, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
return type + ' (' + size + ') {' + joinedEntries + '}';
}
function singleLineValues(xs) {
for (var i = 0; i < xs.length; i++) {
if (indexOf(xs[i], '\n') >= 0) {
return false;
}
}
return true;
}
function getIndent(opts, depth) {
var baseIndent;
if (opts.indent === '\t') {
baseIndent = '\t';
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
baseIndent = $join.call(Array(opts.indent + 1), ' ');
} else {
return null;
}
return {
base: baseIndent,
prev: $join.call(Array(depth + 1), baseIndent)
};
}
function indentedJoin(xs, indent) {
if (xs.length === 0) { return ''; }
var lineJoiner = '\n' + indent.prev + indent.base;
return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
}
function arrObjKeys(obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
var symMap;
if (hasShammedSymbols) {
symMap = {};
for (var k = 0; k < syms.length; k++) {
symMap['$' + syms[k]] = syms[k];
}
}
for (var key in obj) { // eslint-disable-line no-restricted-syntax
if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
continue; // eslint-disable-line no-restricted-syntax, no-continue
} else if ($test.call(/[^\w$]/, key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
if (typeof gOPS === 'function') {
for (var j = 0; j < syms.length; j++) {
if (isEnumerable.call(obj, syms[j])) {
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
}
}
}
return xs;
}
``` | /content/code_sandbox/node_modules/object-inspect/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 4,781 |
```javascript
var test = require('tape');
var inspect = require('../');
var xs = ['a', 'b'];
xs[5] = 'f';
xs[7] = 'j';
xs[8] = 'k';
test('holes', function (t) {
t.plan(1);
t.equal(
inspect(xs),
"[ 'a', 'b', , , , 'f', , 'j', 'k' ]"
);
});
``` | /content/code_sandbox/node_modules/object-inspect/test/holes.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 96 |
```javascript
'use strict';
var inspect = require('../');
var test = require('tape');
var mockProperty = require('mock-property');
test('when Object#hasOwnProperty is deleted', function (t) {
t.plan(1);
var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays
t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty"
t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true }));
t.equal(inspect(arr), '[ 1, , 3 ]');
});
``` | /content/code_sandbox/node_modules/object-inspect/test/has.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 138 |
```javascript
var test = require('tape');
var inspect = require('../');
var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' };
test('interpolate low bytes', function (t) {
t.plan(1);
t.equal(
inspect(obj),
"{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }"
);
});
``` | /content/code_sandbox/node_modules/object-inspect/test/lowbyte.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 97 |
```javascript
'use strict';
var inspect = require('../');
var test = require('tape');
var hasToStringTag = require('has-tostringtag/shams')();
test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) {
t.test('primitives', function (st) {
st.plan(3);
st.equal(inspect(BigInt(-256)), '-256n');
st.equal(inspect(BigInt(0)), '0n');
st.equal(inspect(BigInt(256)), '256n');
});
t.test('objects', function (st) {
st.plan(3);
st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)');
st.equal(inspect(Object(BigInt(0))), 'Object(0n)');
st.equal(inspect(Object(BigInt(256))), 'Object(256n)');
});
t.test('syntactic primitives', function (st) {
st.plan(3);
/* eslint-disable no-new-func */
st.equal(inspect(Function('return -256n')()), '-256n');
st.equal(inspect(Function('return 0n')()), '0n');
st.equal(inspect(Function('return 256n')()), '256n');
});
t.test('toStringTag', { skip: !hasToStringTag }, function (st) {
st.plan(1);
var faker = {};
faker[Symbol.toStringTag] = 'BigInt';
st.equal(
inspect(faker),
'{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }',
'object lying about being a BigInt inspects as an object'
);
});
t.test('numericSeparator', function (st) {
st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false');
st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true');
st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false');
st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true');
st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false');
st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true');
st.end();
});
t.end();
});
``` | /content/code_sandbox/node_modules/object-inspect/test/bigint.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 565 |
```javascript
var inspect = require('../');
var test = require('tape');
var arrow = require('make-arrow-function')();
var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames();
test('function', function (t) {
t.plan(1);
var obj = [1, 2, function f(n) { return n; }, 4];
t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]');
});
test('function name', function (t) {
t.plan(1);
var f = (function () {
return function () {};
}());
f.toString = function toStr() { return 'function xxx () {}'; };
var obj = [1, 2, f, 4];
t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]');
});
test('anon function', function (t) {
var f = (function () {
return function () {};
}());
var obj = [1, 2, f, 4];
t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]');
t.end();
});
test('arrow function', { skip: !arrow }, function (t) {
t.equal(inspect(arrow), '[Function (anonymous)]');
t.end();
});
test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) {
function f() {}
Object.defineProperty(f, 'name', { value: false });
t.equal(f.name, false);
t.equal(
inspect(f),
'[Function: f]',
'named function with falsy `.name` does not hide its original name'
);
function g() {}
Object.defineProperty(g, 'name', { value: true });
t.equal(g.name, true);
t.equal(
inspect(g),
'[Function: true]',
'named function with truthy `.name` hides its original name'
);
var anon = function () {}; // eslint-disable-line func-style
Object.defineProperty(anon, 'name', { value: null });
t.equal(anon.name, null);
t.equal(
inspect(anon),
'[Function (anonymous)]',
'anon function with falsy `.name` does not hide its anonymity'
);
var anon2 = function () {}; // eslint-disable-line func-style
Object.defineProperty(anon2, 'name', { value: 1 });
t.equal(anon2.name, 1);
t.equal(
inspect(anon2),
'[Function: 1]',
'anon function with truthy `.name` hides its anonymity'
);
t.end();
});
``` | /content/code_sandbox/node_modules/object-inspect/test/fn.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 599 |
```javascript
var inspect = require('../');
var test = require('tape');
test('element', function (t) {
t.plan(3);
var elem = {
nodeName: 'div',
attributes: [{ name: 'class', value: 'row' }],
getAttribute: function (key) { return key; },
childNodes: []
};
var obj = [1, elem, 3];
t.deepEqual(inspect(obj), '[ 1, <div class="row"></div>, 3 ]');
t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1, <div class='row'></div>, 3 ]");
t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1, <div class="row"></div>, 3 ]');
});
test('element no attr', function (t) {
t.plan(1);
var elem = {
nodeName: 'div',
getAttribute: function (key) { return key; },
childNodes: []
};
var obj = [1, elem, 3];
t.deepEqual(inspect(obj), '[ 1, <div></div>, 3 ]');
});
test('element with contents', function (t) {
t.plan(1);
var elem = {
nodeName: 'div',
getAttribute: function (key) { return key; },
childNodes: [{ nodeName: 'b' }]
};
var obj = [1, elem, 3];
t.deepEqual(inspect(obj), '[ 1, <div>...</div>, 3 ]');
});
test('element instance', function (t) {
t.plan(1);
var h = global.HTMLElement;
global.HTMLElement = function (name, attr) {
this.nodeName = name;
this.attributes = attr;
};
global.HTMLElement.prototype.getAttribute = function () {};
var elem = new global.HTMLElement('div', []);
var obj = [1, elem, 3];
t.deepEqual(inspect(obj), '[ 1, <div></div>, 3 ]');
global.HTMLElement = h;
});
``` | /content/code_sandbox/node_modules/object-inspect/test/element.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 454 |
```javascript
'use strict';
var inspect = require('../');
var test = require('tape');
var mockProperty = require('mock-property');
var hasSymbols = require('has-symbols/shams')();
var hasToStringTag = require('has-tostringtag/shams')();
test('values', function (t) {
t.plan(1);
var obj = [{}, [], { 'a-b': 5 }];
t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]');
});
test('arrays with properties', function (t) {
t.plan(1);
var arr = [3];
arr.foo = 'bar';
var obj = [1, 2, arr];
obj.baz = 'quux';
obj.index = -1;
t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]');
});
test('has', function (t) {
t.plan(1);
t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true }));
t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }');
});
test('indexOf seen', function (t) {
t.plan(1);
var xs = [1, 2, 3, {}];
xs.push(xs);
var seen = [];
seen.indexOf = undefined;
t.equal(
inspect(xs, {}, 0, seen),
'[ 1, 2, 3, {}, [Circular] ]'
);
});
test('seen seen', function (t) {
t.plan(1);
var xs = [1, 2, 3];
var seen = [xs];
seen.indexOf = undefined;
t.equal(
inspect(xs, {}, 0, seen),
'[Circular]'
);
});
test('seen seen seen', function (t) {
t.plan(1);
var xs = [1, 2, 3];
var seen = [5, xs];
seen.indexOf = undefined;
t.equal(
inspect(xs, {}, 0, seen),
'[Circular]'
);
});
test('symbols', { skip: !hasSymbols }, function (t) {
var sym = Symbol('foo');
t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"');
if (typeof sym === 'symbol') {
// Symbol shams are incapable of differentiating boxed from unboxed symbols
t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"');
}
t.test('toStringTag', { skip: !hasToStringTag }, function (st) {
st.plan(1);
var faker = {};
faker[Symbol.toStringTag] = 'Symbol';
st.equal(
inspect(faker),
'{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }',
'object lying about being a Symbol inspects as an object'
);
});
t.end();
});
test('Map', { skip: typeof Map !== 'function' }, function (t) {
var map = new Map();
map.set({ a: 1 }, ['b']);
map.set(3, NaN);
var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}';
t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents');
t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty');
var nestedMap = new Map();
nestedMap.set(nestedMap, map);
t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work');
t.end();
});
test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) {
var map = new WeakMap();
map.set({ a: 1 }, ['b']);
var expectedString = 'WeakMap { ? }';
t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents');
t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty');
t.end();
});
test('Set', { skip: typeof Set !== 'function' }, function (t) {
var set = new Set();
set.add({ a: 1 });
set.add(['b']);
var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}';
t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents');
t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty');
var nestedSet = new Set();
nestedSet.add(set);
nestedSet.add(nestedSet);
t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work');
t.end();
});
test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) {
var map = new WeakSet();
map.add({ a: 1 });
var expectedString = 'WeakSet { ? }';
t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents');
t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty');
t.end();
});
test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) {
var ref = new WeakRef({ a: 1 });
var expectedString = 'WeakRef { ? }';
t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents');
t.end();
});
test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) {
var registry = new FinalizationRegistry(function () {});
var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}';
t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys');
t.end();
});
test('Strings', function (t) {
var str = 'abc';
t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such');
t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted');
t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted');
t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such');
t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted');
t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted');
t.end();
});
test('Numbers', function (t) {
var num = 42;
t.equal(inspect(num), String(num), 'primitive number shows as such');
t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such');
t.end();
});
test('Booleans', function (t) {
t.equal(inspect(true), String(true), 'primitive true shows as such');
t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such');
t.equal(inspect(false), String(false), 'primitive false shows as such');
t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such');
t.end();
});
test('Date', function (t) {
var now = new Date();
t.equal(inspect(now), String(now), 'Date shows properly');
t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly');
t.end();
});
test('RegExps', function (t) {
t.equal(inspect(/a/g), '/a/g', 'regex shows properly');
t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly');
var match = 'abc abc'.match(/[ab]+/);
delete match.groups; // for node < 10
t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly');
t.end();
});
``` | /content/code_sandbox/node_modules/object-inspect/test/values.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,971 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.