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 var convert = require('./convert'), func = convert('intersectionBy', require('../intersectionBy')); func.placeholder = require('./placeholder'); module.exports = func; ```
/content/code_sandbox/node_modules/lodash/fp/intersectionBy.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
33
```javascript var convert = require('./convert'), func = convert('assignWith', require('../assignWith')); func.placeholder = require('./placeholder'); module.exports = func; ```
/content/code_sandbox/node_modules/lodash/fp/assignWith.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
33
```javascript var convert = require('./convert'), func = convert('isNative', require('../isNative'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func; ```
/content/code_sandbox/node_modules/lodash/fp/isNative.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
39
```javascript var convert = require('./convert'), func = convert('isElement', require('../isElement'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func; ```
/content/code_sandbox/node_modules/lodash/fp/isElement.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
39
```javascript var convert = require('./convert'), func = convert('stubFalse', require('../stubFalse'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func; ```
/content/code_sandbox/node_modules/lodash/fp/stubFalse.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
39
```javascript var convert = require('./convert'), func = convert('isObjectLike', require('../isObjectLike'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func; ```
/content/code_sandbox/node_modules/lodash/fp/isObjectLike.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
39
```javascript module.exports = require('./invert'); ```
/content/code_sandbox/node_modules/lodash/fp/invertObj.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
8
```javascript var convert = require('./convert'), func = convert('mergeWith', require('../mergeWith')); func.placeholder = require('./placeholder'); module.exports = func; ```
/content/code_sandbox/node_modules/lodash/fp/mergeWith.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
33
```javascript /** * Expose `Emitter`. */ if (typeof module !== 'undefined') { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } // Remove event specific arrays for event types that no // one is subscribed for to avoid memory leak. if (callbacks.length === 0) { delete this._callbacks['$' + event]; } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = new Array(arguments.length - 1) , callbacks = this._callbacks['$' + event]; for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; ```
/content/code_sandbox/node_modules/component-emitter/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
862
```javascript var types = require("./lib/types"); // This core module of AST types captures ES5 as it is parsed today by // git://github.com/ariya/esprima.git#master. require("./def/core"); // Feel free to add to or remove from this list of extension modules to // configure the precise type hierarchy that you need. require("./def/es6"); require("./def/es7"); require("./def/mozilla"); require("./def/e4x"); require("./def/fb-harmony"); require("./def/esprima"); require("./def/babel"); types.finalize(); exports.Type = types.Type; exports.builtInTypes = types.builtInTypes; exports.namedTypes = types.namedTypes; exports.builders = types.builders; exports.defineMethod = types.defineMethod; exports.getFieldNames = types.getFieldNames; exports.getFieldValue = types.getFieldValue; exports.eachField = types.eachField; exports.someField = types.someField; exports.getSupertypeNames = types.getSupertypeNames; exports.astNodesAreEquivalent = require("./lib/equiv"); exports.finalize = types.finalize; exports.NodePath = require("./lib/node-path"); exports.PathVisitor = require("./lib/path-visitor"); exports.visit = exports.PathVisitor.visit; ```
/content/code_sandbox/node_modules/ast-types/main.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
256
```javascript /** Used to map aliases to their real names. */ exports.aliasToReal = { // Lodash aliases. 'each': 'forEach', 'eachRight': 'forEachRight', 'entries': 'toPairs', 'entriesIn': 'toPairsIn', 'extend': 'assignIn', 'extendAll': 'assignInAll', 'extendAllWith': 'assignInAllWith', 'extendWith': 'assignInWith', 'first': 'head', // Methods that are curried variants of others. 'conforms': 'conformsTo', 'matches': 'isMatch', 'property': 'get', // Ramda aliases. '__': 'placeholder', 'F': 'stubFalse', 'T': 'stubTrue', 'all': 'every', 'allPass': 'overEvery', 'always': 'constant', 'any': 'some', 'anyPass': 'overSome', 'apply': 'spread', 'assoc': 'set', 'assocPath': 'set', 'complement': 'negate', 'compose': 'flowRight', 'contains': 'includes', 'dissoc': 'unset', 'dissocPath': 'unset', 'dropLast': 'dropRight', 'dropLastWhile': 'dropRightWhile', 'equals': 'isEqual', 'identical': 'eq', 'indexBy': 'keyBy', 'init': 'initial', 'invertObj': 'invert', 'juxt': 'over', 'omitAll': 'omit', 'nAry': 'ary', 'path': 'get', 'pathEq': 'matchesProperty', 'pathOr': 'getOr', 'paths': 'at', 'pickAll': 'pick', 'pipe': 'flow', 'pluck': 'map', 'prop': 'get', 'propEq': 'matchesProperty', 'propOr': 'getOr', 'props': 'at', 'symmetricDifference': 'xor', 'symmetricDifferenceBy': 'xorBy', 'symmetricDifferenceWith': 'xorWith', 'takeLast': 'takeRight', 'takeLastWhile': 'takeRightWhile', 'unapply': 'rest', 'unnest': 'flatten', 'useWith': 'overArgs', 'where': 'conformsTo', 'whereEq': 'isMatch', 'zipObj': 'zipObject' }; /** Used to map ary to method names. */ exports.aryMethod = { '1': [ 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse', 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', 'uniqueId', 'words', 'zipAll' ], '2': [ 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', 'zipObjectDeep' ], '3': [ 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', 'xorWith', 'zipWith' ], '4': [ 'fill', 'setWith', 'updateWith' ] }; /** Used to map ary to rearg configs. */ exports.aryRearg = { '2': [1, 0], '3': [2, 0, 1], '4': [3, 2, 0, 1] }; /** Used to map method names to their iteratee ary. */ exports.iterateeAry = { 'dropRightWhile': 1, 'dropWhile': 1, 'every': 1, 'filter': 1, 'find': 1, 'findFrom': 1, 'findIndex': 1, 'findIndexFrom': 1, 'findKey': 1, 'findLast': 1, 'findLastFrom': 1, 'findLastIndex': 1, 'findLastIndexFrom': 1, 'findLastKey': 1, 'flatMap': 1, 'flatMapDeep': 1, 'flatMapDepth': 1, 'forEach': 1, 'forEachRight': 1, 'forIn': 1, 'forInRight': 1, 'forOwn': 1, 'forOwnRight': 1, 'map': 1, 'mapKeys': 1, 'mapValues': 1, 'partition': 1, 'reduce': 2, 'reduceRight': 2, 'reject': 1, 'remove': 1, 'some': 1, 'takeRightWhile': 1, 'takeWhile': 1, 'times': 1, 'transform': 2 }; /** Used to map method names to iteratee rearg configs. */ exports.iterateeRearg = { 'mapKeys': [1], 'reduceRight': [1, 0] }; /** Used to map method names to rearg configs. */ exports.methodRearg = { 'assignInAllWith': [1, 0], 'assignInWith': [1, 2, 0], 'assignAllWith': [1, 0], 'assignWith': [1, 2, 0], 'differenceBy': [1, 2, 0], 'differenceWith': [1, 2, 0], 'getOr': [2, 1, 0], 'intersectionBy': [1, 2, 0], 'intersectionWith': [1, 2, 0], 'isEqualWith': [1, 2, 0], 'isMatchWith': [2, 1, 0], 'mergeAllWith': [1, 0], 'mergeWith': [1, 2, 0], 'padChars': [2, 1, 0], 'padCharsEnd': [2, 1, 0], 'padCharsStart': [2, 1, 0], 'pullAllBy': [2, 1, 0], 'pullAllWith': [2, 1, 0], 'rangeStep': [1, 2, 0], 'rangeStepRight': [1, 2, 0], 'setWith': [3, 1, 2, 0], 'sortedIndexBy': [2, 1, 0], 'sortedLastIndexBy': [2, 1, 0], 'unionBy': [1, 2, 0], 'unionWith': [1, 2, 0], 'updateWith': [3, 1, 2, 0], 'xorBy': [1, 2, 0], 'xorWith': [1, 2, 0], 'zipWith': [1, 2, 0] }; /** Used to map method names to spread configs. */ exports.methodSpread = { 'assignAll': { 'start': 0 }, 'assignAllWith': { 'start': 0 }, 'assignInAll': { 'start': 0 }, 'assignInAllWith': { 'start': 0 }, 'defaultsAll': { 'start': 0 }, 'defaultsDeepAll': { 'start': 0 }, 'invokeArgs': { 'start': 2 }, 'invokeArgsMap': { 'start': 2 }, 'mergeAll': { 'start': 0 }, 'mergeAllWith': { 'start': 0 }, 'partial': { 'start': 1 }, 'partialRight': { 'start': 1 }, 'without': { 'start': 1 }, 'zipAll': { 'start': 0 } }; /** Used to identify methods which mutate arrays or objects. */ exports.mutate = { 'array': { 'fill': true, 'pull': true, 'pullAll': true, 'pullAllBy': true, 'pullAllWith': true, 'pullAt': true, 'remove': true, 'reverse': true }, 'object': { 'assign': true, 'assignAll': true, 'assignAllWith': true, 'assignIn': true, 'assignInAll': true, 'assignInAllWith': true, 'assignInWith': true, 'assignWith': true, 'defaults': true, 'defaultsAll': true, 'defaultsDeep': true, 'defaultsDeepAll': true, 'merge': true, 'mergeAll': true, 'mergeAllWith': true, 'mergeWith': true, }, 'set': { 'set': true, 'setWith': true, 'unset': true, 'update': true, 'updateWith': true } }; /** Used to map real names to their aliases. */ exports.realToAlias = (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, object = exports.aliasToReal, result = {}; for (var key in object) { var value = object[key]; if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } } return result; }()); /** Used to map method names to other names. */ exports.remap = { 'assignAll': 'assign', 'assignAllWith': 'assignWith', 'assignInAll': 'assignIn', 'assignInAllWith': 'assignInWith', 'curryN': 'curry', 'curryRightN': 'curryRight', 'defaultsAll': 'defaults', 'defaultsDeepAll': 'defaultsDeep', 'findFrom': 'find', 'findIndexFrom': 'findIndex', 'findLastFrom': 'findLast', 'findLastIndexFrom': 'findLastIndex', 'getOr': 'get', 'includesFrom': 'includes', 'indexOfFrom': 'indexOf', 'invokeArgs': 'invoke', 'invokeArgsMap': 'invokeMap', 'lastIndexOfFrom': 'lastIndexOf', 'mergeAll': 'merge', 'mergeAllWith': 'mergeWith', 'padChars': 'pad', 'padCharsEnd': 'padEnd', 'padCharsStart': 'padStart', 'propertyOf': 'get', 'rangeStep': 'range', 'rangeStepRight': 'rangeRight', 'restFrom': 'rest', 'spreadFrom': 'spread', 'trimChars': 'trim', 'trimCharsEnd': 'trimEnd', 'trimCharsStart': 'trimStart', 'zipAll': 'zip' }; /** Used to track methods that skip fixing their arity. */ exports.skipFixed = { 'castArray': true, 'flow': true, 'flowRight': true, 'iteratee': true, 'mixin': true, 'rearg': true, 'runInContext': true }; /** Used to track methods that skip rearranging arguments. */ exports.skipRearg = { 'add': true, 'assign': true, 'assignIn': true, 'bind': true, 'bindKey': true, 'concat': true, 'difference': true, 'divide': true, 'eq': true, 'gt': true, 'gte': true, 'isEqual': true, 'lt': true, 'lte': true, 'matchesProperty': true, 'merge': true, 'multiply': true, 'overArgs': true, 'partial': true, 'partialRight': true, 'propertyOf': true, 'random': true, 'range': true, 'rangeRight': true, 'subtract': true, 'zip': true, 'zipObject': true, 'zipObjectDeep': true }; ```
/content/code_sandbox/node_modules/lodash/fp/_mapping.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,433
```javascript var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var types = require("./types"); var isArray = types.builtInTypes.array; var isNumber = types.builtInTypes.number; var Ap = Array.prototype; var slice = Ap.slice; var map = Ap.map; function Path(value, parentPath, name) { if (!(this instanceof Path)) { throw new Error("Path constructor cannot be invoked without 'new'"); } if (parentPath) { if (!(parentPath instanceof Path)) { throw new Error(""); } } else { parentPath = null; name = null; } // The value encapsulated by this Path, generally equal to // parentPath.value[name] if we have a parentPath. this.value = value; // The immediate parent Path of this Path. this.parentPath = parentPath; // The name of the property of parentPath.value through which this // Path's value was reached. this.name = name; // Calling path.get("child") multiple times always returns the same // child Path object, for both performance and consistency reasons. this.__childCache = null; } var Pp = Path.prototype; function getChildCache(path) { // Lazily create the child cache. This also cheapens cache // invalidation, since you can just reset path.__childCache to null. return path.__childCache || (path.__childCache = Object.create(null)); } function getChildPath(path, name) { var cache = getChildCache(path); var actualChildValue = path.getValueProperty(name); var childPath = cache[name]; if (!hasOwn.call(cache, name) || // Ensure consistency between cache and reality. childPath.value !== actualChildValue) { childPath = cache[name] = new path.constructor( actualChildValue, path, name ); } return childPath; } // This method is designed to be overridden by subclasses that need to // handle missing properties, etc. Pp.getValueProperty = function getValueProperty(name) { return this.value[name]; }; Pp.get = function get(name) { var path = this; var names = arguments; var count = names.length; for (var i = 0; i < count; ++i) { path = getChildPath(path, names[i]); } return path; }; Pp.each = function each(callback, context) { var childPaths = []; var len = this.value.length; var i = 0; // Collect all the original child paths before invoking the callback. for (var i = 0; i < len; ++i) { if (hasOwn.call(this.value, i)) { childPaths[i] = this.get(i); } } // Invoke the callback on just the original child paths, regardless of // any modifications made to the array by the callback. I chose these // semantics over cleverly invoking the callback on new elements because // this way is much easier to reason about. context = context || this; for (i = 0; i < len; ++i) { if (hasOwn.call(childPaths, i)) { callback.call(context, childPaths[i]); } } }; Pp.map = function map(callback, context) { var result = []; this.each(function(childPath) { result.push(callback.call(this, childPath)); }, context); return result; }; Pp.filter = function filter(callback, context) { var result = []; this.each(function(childPath) { if (callback.call(this, childPath)) { result.push(childPath); } }, context); return result; }; function emptyMoves() {} function getMoves(path, offset, start, end) { isArray.assert(path.value); if (offset === 0) { return emptyMoves; } var length = path.value.length; if (length < 1) { return emptyMoves; } var argc = arguments.length; if (argc === 2) { start = 0; end = length; } else if (argc === 3) { start = Math.max(start, 0); end = length; } else { start = Math.max(start, 0); end = Math.min(end, length); } isNumber.assert(start); isNumber.assert(end); var moves = Object.create(null); var cache = getChildCache(path); for (var i = start; i < end; ++i) { if (hasOwn.call(path.value, i)) { var childPath = path.get(i); if (childPath.name !== i) { throw new Error(""); } var newIndex = i + offset; childPath.name = newIndex; moves[newIndex] = childPath; delete cache[i]; } } delete cache.length; return function() { for (var newIndex in moves) { var childPath = moves[newIndex]; if (childPath.name !== +newIndex) { throw new Error(""); } cache[newIndex] = childPath; path.value[newIndex] = childPath.value; } }; } Pp.shift = function shift() { var move = getMoves(this, -1); var result = this.value.shift(); move(); return result; }; Pp.unshift = function unshift(node) { var move = getMoves(this, arguments.length); var result = this.value.unshift.apply(this.value, arguments); move(); return result; }; Pp.push = function push(node) { isArray.assert(this.value); delete getChildCache(this).length return this.value.push.apply(this.value, arguments); }; Pp.pop = function pop() { isArray.assert(this.value); var cache = getChildCache(this); delete cache[this.value.length - 1]; delete cache.length; return this.value.pop(); }; Pp.insertAt = function insertAt(index, node) { var argc = arguments.length; var move = getMoves(this, argc - 1, index); if (move === emptyMoves) { return this; } index = Math.max(index, 0); for (var i = 1; i < argc; ++i) { this.value[index + i - 1] = arguments[i]; } move(); return this; }; Pp.insertBefore = function insertBefore(node) { var pp = this.parentPath; var argc = arguments.length; var insertAtArgs = [this.name]; for (var i = 0; i < argc; ++i) { insertAtArgs.push(arguments[i]); } return pp.insertAt.apply(pp, insertAtArgs); }; Pp.insertAfter = function insertAfter(node) { var pp = this.parentPath; var argc = arguments.length; var insertAtArgs = [this.name + 1]; for (var i = 0; i < argc; ++i) { insertAtArgs.push(arguments[i]); } return pp.insertAt.apply(pp, insertAtArgs); }; function repairRelationshipWithParent(path) { if (!(path instanceof Path)) { throw new Error(""); } var pp = path.parentPath; if (!pp) { // Orphan paths have no relationship to repair. return path; } var parentValue = pp.value; var parentCache = getChildCache(pp); // Make sure parentCache[path.name] is populated. if (parentValue[path.name] === path.value) { parentCache[path.name] = path; } else if (isArray.check(parentValue)) { // Something caused path.name to become out of date, so attempt to // recover by searching for path.value in parentValue. var i = parentValue.indexOf(path.value); if (i >= 0) { parentCache[path.name = i] = path; } } else { // If path.value disagrees with parentValue[path.name], and // path.name is not an array index, let path.value become the new // parentValue[path.name] and update parentCache accordingly. parentValue[path.name] = path.value; parentCache[path.name] = path; } if (parentValue[path.name] !== path.value) { throw new Error(""); } if (path.parentPath.get(path.name) !== path) { throw new Error(""); } return path; } Pp.replace = function replace(replacement) { var results = []; var parentValue = this.parentPath.value; var parentCache = getChildCache(this.parentPath); var count = arguments.length; repairRelationshipWithParent(this); if (isArray.check(parentValue)) { var originalLength = parentValue.length; var move = getMoves(this.parentPath, count - 1, this.name + 1); var spliceArgs = [this.name, 1]; for (var i = 0; i < count; ++i) { spliceArgs.push(arguments[i]); } var splicedOut = parentValue.splice.apply(parentValue, spliceArgs); if (splicedOut[0] !== this.value) { throw new Error(""); } if (parentValue.length !== (originalLength - 1 + count)) { throw new Error(""); } move(); if (count === 0) { delete this.value; delete parentCache[this.name]; this.__childCache = null; } else { if (parentValue[this.name] !== replacement) { throw new Error(""); } if (this.value !== replacement) { this.value = replacement; this.__childCache = null; } for (i = 0; i < count; ++i) { results.push(this.parentPath.get(this.name + i)); } if (results[0] !== this) { throw new Error(""); } } } else if (count === 1) { if (this.value !== replacement) { this.__childCache = null; } this.value = parentValue[this.name] = replacement; results.push(this); } else if (count === 0) { delete parentValue[this.name]; delete this.value; this.__childCache = null; // Leave this path cached as parentCache[this.name], even though // it no longer has a value defined. } else { throw new Error("Could not replace path"); } return results; }; module.exports = Path; ```
/content/code_sandbox/node_modules/ast-types/lib/path.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,277
```javascript var types = require("../lib/types"); var Type = types.Type; var builtin = types.builtInTypes; var isNumber = builtin.number; // An example of constructing a new type with arbitrary constraints from // an existing type. exports.geq = function(than) { return new Type(function(value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); }; // Default value-returning functions that may optionally be passed as a // third argument to Def.prototype.field. exports.defaults = { // Functions were used because (among other reasons) that's the most // elegant way to allow for the emptyArray one always to give a new // array instance. "null": function() { return null }, "emptyArray": function() { return [] }, "false": function() { return false }, "true": function() { return true }, "undefined": function() {} }; var naiveIsPrimitive = Type.or( builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined ); exports.isPrimitive = new Type(function(value) { if (value === null) return true; var type = typeof value; return !(type === "object" || type === "function"); }, naiveIsPrimitive.toString()); ```
/content/code_sandbox/node_modules/ast-types/lib/shared.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
281
```javascript var types = require("./types"); var Type = types.Type; var namedTypes = types.namedTypes; var Node = namedTypes.Node; var Expression = namedTypes.Expression; var isArray = types.builtInTypes.array; var hasOwn = Object.prototype.hasOwnProperty; var b = types.builders; function Scope(path, parentScope) { if (!(this instanceof Scope)) { throw new Error("Scope constructor cannot be invoked without 'new'"); } if (!(path instanceof require("./node-path"))) { throw new Error(""); } ScopeType.assert(path.value); var depth; if (parentScope) { if (!(parentScope instanceof Scope)) { throw new Error(""); } depth = parentScope.depth + 1; } else { parentScope = null; depth = 0; } Object.defineProperties(this, { path: { value: path }, node: { value: path.value }, isGlobal: { value: !parentScope, enumerable: true }, depth: { value: depth }, parent: { value: parentScope }, bindings: { value: {} }, types: { value: {} }, }); } var scopeTypes = [ // Program nodes introduce global scopes. namedTypes.Program, // Function is the supertype of FunctionExpression, // FunctionDeclaration, ArrowExpression, etc. namedTypes.Function, // In case you didn't know, the caught parameter shadows any variable // of the same name in an outer scope. namedTypes.CatchClause ]; var ScopeType = Type.or.apply(Type, scopeTypes); Scope.isEstablishedBy = function(node) { return ScopeType.check(node); }; var Sp = Scope.prototype; // Will be overridden after an instance lazily calls scanScope. Sp.didScan = false; Sp.declares = function(name) { this.scan(); return hasOwn.call(this.bindings, name); }; Sp.declaresType = function(name) { this.scan(); return hasOwn.call(this.types, name); }; Sp.declareTemporary = function(prefix) { if (prefix) { if (!/^[a-z$_]/i.test(prefix)) { throw new Error(""); } } else { prefix = "t$"; } // Include this.depth in the name to make sure the name does not // collide with any variables in nested/enclosing scopes. prefix += this.depth.toString(36) + "$"; this.scan(); var index = 0; while (this.declares(prefix + index)) { ++index; } var name = prefix + index; return this.bindings[name] = types.builders.identifier(name); }; Sp.injectTemporary = function(identifier, init) { identifier || (identifier = this.declareTemporary()); var bodyPath = this.path.get("body"); if (namedTypes.BlockStatement.check(bodyPath.value)) { bodyPath = bodyPath.get("body"); } bodyPath.unshift( b.variableDeclaration( "var", [b.variableDeclarator(identifier, init || null)] ) ); return identifier; }; Sp.scan = function(force) { if (force || !this.didScan) { for (var name in this.bindings) { // Empty out this.bindings, just in cases. delete this.bindings[name]; } scanScope(this.path, this.bindings, this.types); this.didScan = true; } }; Sp.getBindings = function () { this.scan(); return this.bindings; }; Sp.getTypes = function () { this.scan(); return this.types; }; function scanScope(path, bindings, scopeTypes) { var node = path.value; ScopeType.assert(node); if (namedTypes.CatchClause.check(node)) { // A catch clause establishes a new scope but the only variable // bound in that scope is the catch parameter. Any other // declarations create bindings in the outer scope. addPattern(path.get("param"), bindings); } else { recursiveScanScope(path, bindings, scopeTypes); } } function recursiveScanScope(path, bindings, scopeTypes) { var node = path.value; if (path.parent && namedTypes.FunctionExpression.check(path.parent.node) && path.parent.node.id) { addPattern(path.parent.get("id"), bindings); } if (!node) { // None of the remaining cases matter if node is falsy. } else if (isArray.check(node)) { path.each(function(childPath) { recursiveScanChild(childPath, bindings, scopeTypes); }); } else if (namedTypes.Function.check(node)) { path.get("params").each(function(paramPath) { addPattern(paramPath, bindings); }); recursiveScanChild(path.get("body"), bindings, scopeTypes); } else if (namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) { addTypePattern(path.get("id"), scopeTypes); } else if (namedTypes.VariableDeclarator.check(node)) { addPattern(path.get("id"), bindings); recursiveScanChild(path.get("init"), bindings, scopeTypes); } else if (node.type === "ImportSpecifier" || node.type === "ImportNamespaceSpecifier" || node.type === "ImportDefaultSpecifier") { addPattern( // Esprima used to use the .name field to refer to the local // binding identifier for ImportSpecifier nodes, but .id for // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes. // ESTree/Acorn/ESpree use .local for all three node types. path.get(node.local ? "local" : node.name ? "name" : "id"), bindings ); } else if (Node.check(node) && !Expression.check(node)) { types.eachField(node, function(name, child) { var childPath = path.get(name); if (childPath.value !== child) { throw new Error(""); } recursiveScanChild(childPath, bindings, scopeTypes); }); } } function recursiveScanChild(path, bindings, scopeTypes) { var node = path.value; if (!node || Expression.check(node)) { // Ignore falsy values and Expressions. } else if (namedTypes.FunctionDeclaration.check(node)) { addPattern(path.get("id"), bindings); } else if (namedTypes.ClassDeclaration && namedTypes.ClassDeclaration.check(node)) { addPattern(path.get("id"), bindings); } else if (ScopeType.check(node)) { if (namedTypes.CatchClause.check(node)) { var catchParamName = node.param.name; var hadBinding = hasOwn.call(bindings, catchParamName); // Any declarations that occur inside the catch body that do // not have the same name as the catch parameter should count // as bindings in the outer scope. recursiveScanScope(path.get("body"), bindings, scopeTypes); // If a new binding matching the catch parameter name was // created while scanning the catch body, ignore it because it // actually refers to the catch parameter and not the outer // scope that we're currently scanning. if (!hadBinding) { delete bindings[catchParamName]; } } } else { recursiveScanScope(path, bindings, scopeTypes); } } function addPattern(patternPath, bindings) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn.call(bindings, pattern.name)) { bindings[pattern.name].push(patternPath); } else { bindings[pattern.name] = [patternPath]; } } else if (namedTypes.ObjectPattern && namedTypes.ObjectPattern.check(pattern)) { patternPath.get('properties').each(function(propertyPath) { var property = propertyPath.value; if (namedTypes.Pattern.check(property)) { addPattern(propertyPath, bindings); } else if (namedTypes.Property.check(property)) { addPattern(propertyPath.get('value'), bindings); } else if (namedTypes.SpreadProperty && namedTypes.SpreadProperty.check(property)) { addPattern(propertyPath.get('argument'), bindings); } }); } else if (namedTypes.ArrayPattern && namedTypes.ArrayPattern.check(pattern)) { patternPath.get('elements').each(function(elementPath) { var element = elementPath.value; if (namedTypes.Pattern.check(element)) { addPattern(elementPath, bindings); } else if (namedTypes.SpreadElement && namedTypes.SpreadElement.check(element)) { addPattern(elementPath.get("argument"), bindings); } }); } else if (namedTypes.PropertyPattern && namedTypes.PropertyPattern.check(pattern)) { addPattern(patternPath.get('pattern'), bindings); } else if ((namedTypes.SpreadElementPattern && namedTypes.SpreadElementPattern.check(pattern)) || (namedTypes.SpreadPropertyPattern && namedTypes.SpreadPropertyPattern.check(pattern))) { addPattern(patternPath.get('argument'), bindings); } } function addTypePattern(patternPath, types) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn.call(types, pattern.name)) { types[pattern.name].push(patternPath); } else { types[pattern.name] = [patternPath]; } } } Sp.lookup = function(name) { for (var scope = this; scope; scope = scope.parent) if (scope.declares(name)) break; return scope; }; Sp.lookupType = function(name) { for (var scope = this; scope; scope = scope.parent) if (scope.declaresType(name)) break; return scope; }; Sp.getGlobalScope = function() { var scope = this; while (!scope.isGlobal) scope = scope.parent; return scope; }; module.exports = Scope; ```
/content/code_sandbox/node_modules/ast-types/lib/scope.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,137
```javascript var types = require("../main"); var getFieldNames = types.getFieldNames; var getFieldValue = types.getFieldValue; var isArray = types.builtInTypes.array; var isObject = types.builtInTypes.object; var isDate = types.builtInTypes.Date; var isRegExp = types.builtInTypes.RegExp; var hasOwn = Object.prototype.hasOwnProperty; function astNodesAreEquivalent(a, b, problemPath) { if (isArray.check(problemPath)) { problemPath.length = 0; } else { problemPath = null; } return areEquivalent(a, b, problemPath); } astNodesAreEquivalent.assert = function(a, b) { var problemPath = []; if (!astNodesAreEquivalent(a, b, problemPath)) { if (problemPath.length === 0) { if (a !== b) { throw new Error("Nodes must be equal"); } } else { throw new Error( "Nodes differ in the following path: " + problemPath.map(subscriptForProperty).join("") ); } } }; function subscriptForProperty(property) { if (/[_$a-z][_$a-z0-9]*/i.test(property)) { return "." + property; } return "[" + JSON.stringify(property) + "]"; } function areEquivalent(a, b, problemPath) { if (a === b) { return true; } if (isArray.check(a)) { return arraysAreEquivalent(a, b, problemPath); } if (isObject.check(a)) { return objectsAreEquivalent(a, b, problemPath); } if (isDate.check(a)) { return isDate.check(b) && (+a === +b); } if (isRegExp.check(a)) { return isRegExp.check(b) && ( a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.ignoreCase === b.ignoreCase ); } return a == b; } function arraysAreEquivalent(a, b, problemPath) { isArray.assert(a); var aLength = a.length; if (!isArray.check(b) || b.length !== aLength) { if (problemPath) { problemPath.push("length"); } return false; } for (var i = 0; i < aLength; ++i) { if (problemPath) { problemPath.push(i); } if (i in a !== i in b) { return false; } if (!areEquivalent(a[i], b[i], problemPath)) { return false; } if (problemPath) { var problemPathTail = problemPath.pop(); if (problemPathTail !== i) { throw new Error("" + problemPathTail); } } } return true; } function objectsAreEquivalent(a, b, problemPath) { isObject.assert(a); if (!isObject.check(b)) { return false; } // Fast path for a common property of AST nodes. if (a.type !== b.type) { if (problemPath) { problemPath.push("type"); } return false; } var aNames = getFieldNames(a); var aNameCount = aNames.length; var bNames = getFieldNames(b); var bNameCount = bNames.length; if (aNameCount === bNameCount) { for (var i = 0; i < aNameCount; ++i) { var name = aNames[i]; var aChild = getFieldValue(a, name); var bChild = getFieldValue(b, name); if (problemPath) { problemPath.push(name); } if (!areEquivalent(aChild, bChild, problemPath)) { return false; } if (problemPath) { var problemPathTail = problemPath.pop(); if (problemPathTail !== name) { throw new Error("" + problemPathTail); } } } return true; } if (!problemPath) { return false; } // Since aNameCount !== bNameCount, we need to find some name that's // missing in aNames but present in bNames, or vice-versa. var seenNames = Object.create(null); for (i = 0; i < aNameCount; ++i) { seenNames[aNames[i]] = true; } for (i = 0; i < bNameCount; ++i) { name = bNames[i]; if (!hasOwn.call(seenNames, name)) { problemPath.push(name); return false; } delete seenNames[name]; } for (name in seenNames) { problemPath.push(name); break; } return false; } module.exports = astNodesAreEquivalent; ```
/content/code_sandbox/node_modules/ast-types/lib/equiv.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,056
```javascript var types = require("./types"); var NodePath = require("./node-path"); var Printable = types.namedTypes.Printable; var isArray = types.builtInTypes.array; var isObject = types.builtInTypes.object; var isFunction = types.builtInTypes.function; var hasOwn = Object.prototype.hasOwnProperty; var undefined; function PathVisitor() { if (!(this instanceof PathVisitor)) { throw new Error( "PathVisitor constructor cannot be invoked without 'new'" ); } // Permanent state. this._reusableContextStack = []; this._methodNameTable = computeMethodNameTable(this); this._shouldVisitComments = hasOwn.call(this._methodNameTable, "Block") || hasOwn.call(this._methodNameTable, "Line"); this.Context = makeContextConstructor(this); // State reset every time PathVisitor.prototype.visit is called. this._visiting = false; this._changeReported = false; } function computeMethodNameTable(visitor) { var typeNames = Object.create(null); for (var methodName in visitor) { if (/^visit[A-Z]/.test(methodName)) { typeNames[methodName.slice("visit".length)] = true; } } var supertypeTable = types.computeSupertypeLookupTable(typeNames); var methodNameTable = Object.create(null); var typeNames = Object.keys(supertypeTable); var typeNameCount = typeNames.length; for (var i = 0; i < typeNameCount; ++i) { var typeName = typeNames[i]; methodName = "visit" + supertypeTable[typeName]; if (isFunction.check(visitor[methodName])) { methodNameTable[typeName] = methodName; } } return methodNameTable; } PathVisitor.fromMethodsObject = function fromMethodsObject(methods) { if (methods instanceof PathVisitor) { return methods; } if (!isObject.check(methods)) { // An empty visitor? return new PathVisitor; } function Visitor() { if (!(this instanceof Visitor)) { throw new Error( "Visitor constructor cannot be invoked without 'new'" ); } PathVisitor.call(this); } var Vp = Visitor.prototype = Object.create(PVp); Vp.constructor = Visitor; extend(Vp, methods); extend(Visitor, PathVisitor); isFunction.assert(Visitor.fromMethodsObject); isFunction.assert(Visitor.visit); return new Visitor; }; function extend(target, source) { for (var property in source) { if (hasOwn.call(source, property)) { target[property] = source[property]; } } return target; } PathVisitor.visit = function visit(node, methods) { return PathVisitor.fromMethodsObject(methods).visit(node); }; var PVp = PathVisitor.prototype; PVp.visit = function() { if (this._visiting) { throw new Error( "Recursively calling visitor.visit(path) resets visitor state. " + "Try this.visit(path) or this.traverse(path) instead." ); } // Private state that needs to be reset before every traversal. this._visiting = true; this._changeReported = false; this._abortRequested = false; var argc = arguments.length; var args = new Array(argc) for (var i = 0; i < argc; ++i) { args[i] = arguments[i]; } if (!(args[0] instanceof NodePath)) { args[0] = new NodePath({ root: args[0] }).get("root"); } // Called with the same arguments as .visit. this.reset.apply(this, args); try { var root = this.visitWithoutReset(args[0]); var didNotThrow = true; } finally { this._visiting = false; if (!didNotThrow && this._abortRequested) { // If this.visitWithoutReset threw an exception and // this._abortRequested was set to true, return the root of // the AST instead of letting the exception propagate, so that // client code does not have to provide a try-catch block to // intercept the AbortRequest exception. Other kinds of // exceptions will propagate without being intercepted and // rethrown by a catch block, so their stacks will accurately // reflect the original throwing context. return args[0].value; } } return root; }; PVp.AbortRequest = function AbortRequest() {}; PVp.abort = function() { var visitor = this; visitor._abortRequested = true; var request = new visitor.AbortRequest(); // If you decide to catch this exception and stop it from propagating, // make sure to call its cancel method to avoid silencing other // exceptions that might be thrown later in the traversal. request.cancel = function() { visitor._abortRequested = false; }; throw request; }; PVp.reset = function(path/*, additional arguments */) { // Empty stub; may be reassigned or overridden by subclasses. }; PVp.visitWithoutReset = function(path) { if (this instanceof this.Context) { // Since this.Context.prototype === this, there's a chance we // might accidentally call context.visitWithoutReset. If that // happens, re-invoke the method against context.visitor. return this.visitor.visitWithoutReset(path); } if (!(path instanceof NodePath)) { throw new Error(""); } var value = path.value; var methodName = value && typeof value === "object" && typeof value.type === "string" && this._methodNameTable[value.type]; if (methodName) { var context = this.acquireContext(path); try { return context.invokeVisitorMethod(methodName); } finally { this.releaseContext(context); } } else { // If there was no visitor method to call, visit the children of // this node generically. return visitChildren(path, this); } }; function visitChildren(path, visitor) { if (!(path instanceof NodePath)) { throw new Error(""); } if (!(visitor instanceof PathVisitor)) { throw new Error(""); } var value = path.value; if (isArray.check(value)) { path.each(visitor.visitWithoutReset, visitor); } else if (!isObject.check(value)) { // No children to visit. } else { var childNames = types.getFieldNames(value); // The .comments field of the Node type is hidden, so we only // visit it if the visitor defines visitBlock or visitLine, and // value.comments is defined. if (visitor._shouldVisitComments && value.comments && childNames.indexOf("comments") < 0) { childNames.push("comments"); } var childCount = childNames.length; var childPaths = []; for (var i = 0; i < childCount; ++i) { var childName = childNames[i]; if (!hasOwn.call(value, childName)) { value[childName] = types.getFieldValue(value, childName); } childPaths.push(path.get(childName)); } for (var i = 0; i < childCount; ++i) { visitor.visitWithoutReset(childPaths[i]); } } return path.value; } PVp.acquireContext = function(path) { if (this._reusableContextStack.length === 0) { return new this.Context(path); } return this._reusableContextStack.pop().reset(path); }; PVp.releaseContext = function(context) { if (!(context instanceof this.Context)) { throw new Error(""); } this._reusableContextStack.push(context); context.currentPath = null; }; PVp.reportChanged = function() { this._changeReported = true; }; PVp.wasChangeReported = function() { return this._changeReported; }; function makeContextConstructor(visitor) { function Context(path) { if (!(this instanceof Context)) { throw new Error(""); } if (!(this instanceof PathVisitor)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } Object.defineProperty(this, "visitor", { value: visitor, writable: false, enumerable: true, configurable: false }); this.currentPath = path; this.needToCallTraverse = true; Object.seal(this); } if (!(visitor instanceof PathVisitor)) { throw new Error(""); } // Note that the visitor object is the prototype of Context.prototype, // so all visitor methods are inherited by context objects. var Cp = Context.prototype = Object.create(visitor); Cp.constructor = Context; extend(Cp, sharedContextProtoMethods); return Context; } // Every PathVisitor has a different this.Context constructor and // this.Context.prototype object, but those prototypes can all use the // same reset, invokeVisitorMethod, and traverse function objects. var sharedContextProtoMethods = Object.create(null); sharedContextProtoMethods.reset = function reset(path) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } this.currentPath = path; this.needToCallTraverse = true; return this; }; sharedContextProtoMethods.invokeVisitorMethod = function invokeVisitorMethod(methodName) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } var result = this.visitor[methodName].call(this, this.currentPath); if (result === false) { // Visitor methods return false to indicate that they have handled // their own traversal needs, and we should not complain if // this.needToCallTraverse is still true. this.needToCallTraverse = false; } else if (result !== undefined) { // Any other non-undefined value returned from the visitor method // is interpreted as a replacement value. this.currentPath = this.currentPath.replace(result)[0]; if (this.needToCallTraverse) { // If this.traverse still hasn't been called, visit the // children of the replacement node. this.traverse(this.currentPath); } } if (this.needToCallTraverse !== false) { throw new Error( "Must either call this.traverse or return false in " + methodName ); } var path = this.currentPath; return path && path.value; }; sharedContextProtoMethods.traverse = function traverse(path, newVisitor) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } this.needToCallTraverse = false; return visitChildren(path, PathVisitor.fromMethodsObject( newVisitor || this.visitor )); }; sharedContextProtoMethods.visit = function visit(path, newVisitor) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } this.needToCallTraverse = false; return PathVisitor.fromMethodsObject( newVisitor || this.visitor ).visitWithoutReset(path); }; sharedContextProtoMethods.reportChanged = function reportChanged() { this.visitor.reportChanged(); }; sharedContextProtoMethods.abort = function abort() { this.needToCallTraverse = false; this.visitor.abort(); }; module.exports = PathVisitor; ```
/content/code_sandbox/node_modules/ast-types/lib/path-visitor.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,545
```javascript var Ap = Array.prototype; var slice = Ap.slice; var map = Ap.map; var each = Ap.forEach; var Op = Object.prototype; var objToStr = Op.toString; var funObjStr = objToStr.call(function(){}); var strObjStr = objToStr.call(""); var hasOwn = Op.hasOwnProperty; // A type is an object with a .check method that takes a value and returns // true or false according to whether the value matches the type. function Type(check, name) { var self = this; if (!(self instanceof Type)) { throw new Error("Type constructor cannot be invoked without 'new'"); } // Unfortunately we can't elegantly reuse isFunction and isString, // here, because this code is executed while defining those types. if (objToStr.call(check) !== funObjStr) { throw new Error(check + " is not a function"); } // The `name` parameter can be either a function or a string. var nameObjStr = objToStr.call(name); if (!(nameObjStr === funObjStr || nameObjStr === strObjStr)) { throw new Error(name + " is neither a function nor a string"); } Object.defineProperties(self, { name: { value: name }, check: { value: function(value, deep) { var result = check.call(self, value, deep); if (!result && deep && objToStr.call(deep) === funObjStr) deep(self, value); return result; } } }); } var Tp = Type.prototype; // Throughout this file we use Object.defineProperty to prevent // redefinition of exported properties. exports.Type = Type; // Like .check, except that failure triggers an AssertionError. Tp.assert = function(value, deep) { if (!this.check(value, deep)) { var str = shallowStringify(value); throw new Error(str + " does not match type " + this); } return true; }; function shallowStringify(value) { if (isObject.check(value)) return "{" + Object.keys(value).map(function(key) { return key + ": " + value[key]; }).join(", ") + "}"; if (isArray.check(value)) return "[" + value.map(shallowStringify).join(", ") + "]"; return JSON.stringify(value); } Tp.toString = function() { var name = this.name; if (isString.check(name)) return name; if (isFunction.check(name)) return name.call(this) + ""; return name + " type"; }; var builtInCtorFns = []; var builtInCtorTypes = []; var builtInTypes = {}; exports.builtInTypes = builtInTypes; function defBuiltInType(example, name) { var objStr = objToStr.call(example); var type = new Type(function(value) { return objToStr.call(value) === objStr; }, name); builtInTypes[name] = type; if (example && typeof example.constructor === "function") { builtInCtorFns.push(example.constructor); builtInCtorTypes.push(type); } return type; } // These types check the underlying [[Class]] attribute of the given // value, rather than using the problematic typeof operator. Note however // that no subtyping is considered; so, for instance, isObject.check // returns false for [], /./, new Date, and null. var isString = defBuiltInType("truthy", "string"); var isFunction = defBuiltInType(function(){}, "function"); var isArray = defBuiltInType([], "array"); var isObject = defBuiltInType({}, "object"); var isRegExp = defBuiltInType(/./, "RegExp"); var isDate = defBuiltInType(new Date, "Date"); var isNumber = defBuiltInType(3, "number"); var isBoolean = defBuiltInType(true, "boolean"); var isNull = defBuiltInType(null, "null"); var isUndefined = defBuiltInType(void 0, "undefined"); // There are a number of idiomatic ways of expressing types, so this // function serves to coerce them all to actual Type objects. Note that // providing the name argument is not necessary in most cases. function toType(from, name) { // The toType function should of course be idempotent. if (from instanceof Type) return from; // The Def type is used as a helper for constructing compound // interface types for AST nodes. if (from instanceof Def) return from.type; // Support [ElemType] syntax. if (isArray.check(from)) return Type.fromArray(from); // Support { someField: FieldType, ... } syntax. if (isObject.check(from)) return Type.fromObject(from); if (isFunction.check(from)) { var bicfIndex = builtInCtorFns.indexOf(from); if (bicfIndex >= 0) { return builtInCtorTypes[bicfIndex]; } // If isFunction.check(from), and from is not a built-in // constructor, assume from is a binary predicate function we can // use to define the type. return new Type(from, name); } // As a last resort, toType returns a type that matches any value that // is === from. This is primarily useful for literal values like // toType(null), but it has the additional advantage of allowing // toType to be a total function. return new Type(function(value) { return value === from; }, isUndefined.check(name) ? function() { return from + ""; } : name); } // Returns a type that matches the given value iff any of type1, type2, // etc. match the value. Type.or = function(/* type1, type2, ... */) { var types = []; var len = arguments.length; for (var i = 0; i < len; ++i) types.push(toType(arguments[i])); return new Type(function(value, deep) { for (var i = 0; i < len; ++i) if (types[i].check(value, deep)) return true; return false; }, function() { return types.join(" | "); }); }; Type.fromArray = function(arr) { if (!isArray.check(arr)) { throw new Error(""); } if (arr.length !== 1) { throw new Error("only one element type is permitted for typed arrays"); } return toType(arr[0]).arrayOf(); }; Tp.arrayOf = function() { var elemType = this; return new Type(function(value, deep) { return isArray.check(value) && value.every(function(elem) { return elemType.check(elem, deep); }); }, function() { return "[" + elemType + "]"; }); }; Type.fromObject = function(obj) { var fields = Object.keys(obj).map(function(name) { return new Field(name, obj[name]); }); return new Type(function(value, deep) { return isObject.check(value) && fields.every(function(field) { return field.type.check(value[field.name], deep); }); }, function() { return "{ " + fields.join(", ") + " }"; }); }; function Field(name, type, defaultFn, hidden) { var self = this; if (!(self instanceof Field)) { throw new Error("Field constructor cannot be invoked without 'new'"); } isString.assert(name); type = toType(type); var properties = { name: { value: name }, type: { value: type }, hidden: { value: !!hidden } }; if (isFunction.check(defaultFn)) { properties.defaultFn = { value: defaultFn }; } Object.defineProperties(self, properties); } var Fp = Field.prototype; Fp.toString = function() { return JSON.stringify(this.name) + ": " + this.type; }; Fp.getValue = function(obj) { var value = obj[this.name]; if (!isUndefined.check(value)) return value; if (this.defaultFn) value = this.defaultFn.call(obj); return value; }; // Define a type whose name is registered in a namespace (the defCache) so // that future definitions will return the same type given the same name. // In particular, this system allows for circular and forward definitions. // The Def object d returned from Type.def may be used to configure the // type d.type by calling methods such as d.bases, d.build, and d.field. Type.def = function(typeName) { isString.assert(typeName); return hasOwn.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new Def(typeName); }; // In order to return the same Def instance every time Type.def is called // with a particular name, those instances need to be stored in a cache. var defCache = Object.create(null); function Def(typeName) { var self = this; if (!(self instanceof Def)) { throw new Error("Def constructor cannot be invoked without 'new'"); } Object.defineProperties(self, { typeName: { value: typeName }, baseNames: { value: [] }, ownFields: { value: Object.create(null) }, // These two are populated during finalization. allSupertypes: { value: Object.create(null) }, // Includes own typeName. supertypeList: { value: [] }, // Linear inheritance hierarchy. allFields: { value: Object.create(null) }, // Includes inherited fields. fieldNames: { value: [] }, // Non-hidden keys of allFields. type: { value: new Type(function(value, deep) { return self.check(value, deep); }, typeName) } }); } Def.fromValue = function(value) { if (value && typeof value === "object") { var type = value.type; if (typeof type === "string" && hasOwn.call(defCache, type)) { var d = defCache[type]; if (d.finalized) { return d; } } } return null; }; var Dp = Def.prototype; Dp.isSupertypeOf = function(that) { if (that instanceof Def) { if (this.finalized !== true || that.finalized !== true) { throw new Error(""); } return hasOwn.call(that.allSupertypes, this.typeName); } else { throw new Error(that + " is not a Def"); } }; // Note that the list returned by this function is a copy of the internal // supertypeList, *without* the typeName itself as the first element. exports.getSupertypeNames = function(typeName) { if (!hasOwn.call(defCache, typeName)) { throw new Error(""); } var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } return d.supertypeList.slice(1); }; // Returns an object mapping from every known type in the defCache to the // most specific supertype whose name is an own property of the candidates // object. exports.computeSupertypeLookupTable = function(candidates) { var table = {}; var typeNames = Object.keys(defCache); var typeNameCount = typeNames.length; for (var i = 0; i < typeNameCount; ++i) { var typeName = typeNames[i]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error("" + typeName); } for (var j = 0; j < d.supertypeList.length; ++j) { var superTypeName = d.supertypeList[j]; if (hasOwn.call(candidates, superTypeName)) { table[typeName] = superTypeName; break; } } } return table; }; Dp.checkAllFields = function(value, deep) { var allFields = this.allFields; if (this.finalized !== true) { throw new Error("" + this.typeName); } function checkFieldByName(name) { var field = allFields[name]; var type = field.type; var child = field.getValue(value); return type.check(child, deep); } return isObject.check(value) && Object.keys(allFields).every(checkFieldByName); }; Dp.check = function(value, deep) { if (this.finalized !== true) { throw new Error( "prematurely checking unfinalized type " + this.typeName ); } // A Def type can only match an object value. if (!isObject.check(value)) return false; var vDef = Def.fromValue(value); if (!vDef) { // If we couldn't infer the Def associated with the given value, // and we expected it to be a SourceLocation or a Position, it was // probably just missing a "type" field (because Esprima does not // assign a type property to such nodes). Be optimistic and let // this.checkAllFields make the final decision. if (this.typeName === "SourceLocation" || this.typeName === "Position") { return this.checkAllFields(value, deep); } // Calling this.checkAllFields for any other type of node is both // bad for performance and way too forgiving. return false; } // If checking deeply and vDef === this, then we only need to call // checkAllFields once. Calling checkAllFields is too strict when deep // is false, because then we only care about this.isSupertypeOf(vDef). if (deep && vDef === this) return this.checkAllFields(value, deep); // In most cases we rely exclusively on isSupertypeOf to make O(1) // subtyping determinations. This suffices in most situations outside // of unit tests, since interface conformance is checked whenever new // instances are created using builder functions. if (!this.isSupertypeOf(vDef)) return false; // The exception is when deep is true; then, we recursively check all // fields. if (!deep) return true; // Use the more specific Def (vDef) to perform the deep check, but // shallow-check fields defined by the less specific Def (this). return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false); }; Dp.bases = function() { var args = slice.call(arguments); var bases = this.baseNames; if (this.finalized) { if (args.length !== bases.length) { throw new Error(""); } for (var i = 0; i < args.length; i++) { if (args[i] !== bases[i]) { throw new Error(""); } } return this; } args.forEach(function(baseName) { isString.assert(baseName); // This indexOf lookup may be O(n), but the typical number of base // names is very small, and indexOf is a native Array method. if (bases.indexOf(baseName) < 0) bases.push(baseName); }); return this; // For chaining. }; // False by default until .build(...) is called on an instance. Object.defineProperty(Dp, "buildable", { value: false }); var builders = {}; exports.builders = builders; // This object is used as prototype for any node created by a builder. var nodePrototype = {}; // Call this function to define a new method to be shared by all AST // nodes. The replaced method (if any) is returned for easy wrapping. exports.defineMethod = function(name, func) { var old = nodePrototype[name]; // Pass undefined as func to delete nodePrototype[name]. if (isUndefined.check(func)) { delete nodePrototype[name]; } else { isFunction.assert(func); Object.defineProperty(nodePrototype, name, { enumerable: true, // For discoverability. configurable: true, // For delete proto[name]. value: func }); } return old; }; var isArrayOfString = isString.arrayOf(); // Calling the .build method of a Def simultaneously marks the type as // buildable (by defining builders[getBuilderName(typeName)]) and // specifies the order of arguments that should be passed to the builder // function to create an instance of the type. Dp.build = function(/* param1, param2, ... */) { var self = this; var newBuildParams = slice.call(arguments); isArrayOfString.assert(newBuildParams); // Calling Def.prototype.build multiple times has the effect of merely // redefining this property. Object.defineProperty(self, "buildParams", { value: newBuildParams, writable: false, enumerable: false, configurable: true }); if (self.buildable) { // If this Def is already buildable, update self.buildParams and // continue using the old builder function. return self; } // Every buildable type will have its "type" field filled in // automatically. This includes types that are not subtypes of Node, // like SourceLocation, but that seems harmless (TODO?). self.field("type", String, function() { return self.typeName }); // Override Dp.buildable for this Def instance. Object.defineProperty(self, "buildable", { value: true }); Object.defineProperty(builders, getBuilderName(self.typeName), { enumerable: true, value: function() { var args = arguments; var argc = args.length; var built = Object.create(nodePrototype); if (!self.finalized) { throw new Error( "attempting to instantiate unfinalized type " + self.typeName ); } function add(param, i) { if (hasOwn.call(built, param)) return; var all = self.allFields; if (!hasOwn.call(all, param)) { throw new Error("" + param); } var field = all[param]; var type = field.type; var value; if (isNumber.check(i) && i < argc) { value = args[i]; } else if (field.defaultFn) { // Expose the partially-built object to the default // function as its `this` object. value = field.defaultFn.call(built); } else { var message = "no value or default function given for field " + JSON.stringify(param) + " of " + self.typeName + "(" + self.buildParams.map(function(name) { return all[name]; }).join(", ") + ")"; throw new Error(message); } if (!type.check(value)) { throw new Error( shallowStringify(value) + " does not match field " + field + " of type " + self.typeName ); } // TODO Could attach getters and setters here to enforce // dynamic type safety. built[param] = value; } self.buildParams.forEach(function(param, i) { add(param, i); }); Object.keys(self.allFields).forEach(function(param) { add(param); // Use the default value. }); // Make sure that the "type" field was filled automatically. if (built.type !== self.typeName) { throw new Error(""); } return built; } }); return self; // For chaining. }; function getBuilderName(typeName) { return typeName.replace(/^[A-Z]+/, function(upperCasePrefix) { var len = upperCasePrefix.length; switch (len) { case 0: return ""; // If there's only one initial capital letter, just lower-case it. case 1: return upperCasePrefix.toLowerCase(); default: // If there's more than one initial capital letter, lower-case // all but the last one, so that XMLDefaultDeclaration (for // example) becomes xmlDefaultDeclaration. return upperCasePrefix.slice( 0, len - 1).toLowerCase() + upperCasePrefix.charAt(len - 1); } }); } exports.getBuilderName = getBuilderName; function getStatementBuilderName(typeName) { typeName = getBuilderName(typeName); return typeName.replace(/(Expression)?$/, "Statement"); } exports.getStatementBuilderName = getStatementBuilderName; // The reason fields are specified using .field(...) instead of an object // literal syntax is somewhat subtle: the object literal syntax would // support only one key and one value, but with .field(...) we can pass // any number of arguments to specify the field. Dp.field = function(name, type, defaultFn, hidden) { if (this.finalized) { console.error("Ignoring attempt to redefine field " + JSON.stringify(name) + " of finalized type " + JSON.stringify(this.typeName)); return this; } this.ownFields[name] = new Field(name, type, defaultFn, hidden); return this; // For chaining. }; var namedTypes = {}; exports.namedTypes = namedTypes; // Like Object.keys, but aware of what fields each AST type should have. function getFieldNames(object) { var d = Def.fromValue(object); if (d) { return d.fieldNames.slice(0); } if ("type" in object) { throw new Error( "did not recognize object of type " + JSON.stringify(object.type) ); } return Object.keys(object); } exports.getFieldNames = getFieldNames; // Get the value of an object property, taking object.type and default // functions into account. function getFieldValue(object, fieldName) { var d = Def.fromValue(object); if (d) { var field = d.allFields[fieldName]; if (field) { return field.getValue(object); } } return object[fieldName]; } exports.getFieldValue = getFieldValue; // Iterate over all defined fields of an object, including those missing // or undefined, passing each field name and effective value (as returned // by getFieldValue) to the callback. If the object has no corresponding // Def, the callback will never be called. exports.eachField = function(object, callback, context) { getFieldNames(object).forEach(function(name) { callback.call(this, name, getFieldValue(object, name)); }, context); }; // Similar to eachField, except that iteration stops as soon as the // callback returns a truthy value. Like Array.prototype.some, the final // result is either true or false to indicates whether the callback // returned true for any element or not. exports.someField = function(object, callback, context) { return getFieldNames(object).some(function(name) { return callback.call(this, name, getFieldValue(object, name)); }, context); }; // This property will be overridden as true by individual Def instances // when they are finalized. Object.defineProperty(Dp, "finalized", { value: false }); Dp.finalize = function() { var self = this; // It's not an error to finalize a type more than once, but only the // first call to .finalize does anything. if (!self.finalized) { var allFields = self.allFields; var allSupertypes = self.allSupertypes; self.baseNames.forEach(function(name) { var def = defCache[name]; if (def instanceof Def) { def.finalize(); extend(allFields, def.allFields); extend(allSupertypes, def.allSupertypes); } else { var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(self.typeName); throw new Error(message); } }); // TODO Warn if fields are overridden with incompatible types. extend(allFields, self.ownFields); allSupertypes[self.typeName] = self; self.fieldNames.length = 0; for (var fieldName in allFields) { if (hasOwn.call(allFields, fieldName) && !allFields[fieldName].hidden) { self.fieldNames.push(fieldName); } } // Types are exported only once they have been finalized. Object.defineProperty(namedTypes, self.typeName, { enumerable: true, value: self.type }); Object.defineProperty(self, "finalized", { value: true }); // A linearization of the inheritance hierarchy. populateSupertypeList(self.typeName, self.supertypeList); if (self.buildable && self.supertypeList.lastIndexOf("Expression") >= 0) { wrapExpressionBuilderWithStatement(self.typeName); } } }; // Adds an additional builder for Expression subtypes // that wraps the built Expression in an ExpressionStatements. function wrapExpressionBuilderWithStatement(typeName) { var wrapperName = getStatementBuilderName(typeName); // skip if the builder already exists if (builders[wrapperName]) return; // the builder function to wrap with builders.ExpressionStatement var wrapped = builders[getBuilderName(typeName)]; // skip if there is nothing to wrap if (!wrapped) return; builders[wrapperName] = function() { return builders.expressionStatement(wrapped.apply(builders, arguments)); }; } function populateSupertypeList(typeName, list) { list.length = 0; list.push(typeName); var lastSeen = Object.create(null); for (var pos = 0; pos < list.length; ++pos) { typeName = list[pos]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } // If we saw typeName earlier in the breadth-first traversal, // delete the last-seen occurrence. if (hasOwn.call(lastSeen, typeName)) { delete list[lastSeen[typeName]]; } // Record the new index of the last-seen occurrence of typeName. lastSeen[typeName] = pos; // Enqueue the base names of this type. list.push.apply(list, d.baseNames); } // Compaction loop to remove array holes. for (var to = 0, from = to, len = list.length; from < len; ++from) { if (hasOwn.call(list, from)) { list[to++] = list[from]; } } list.length = to; } function extend(into, from) { Object.keys(from).forEach(function(name) { into[name] = from[name]; }); return into; }; exports.finalize = function() { Object.keys(defCache).forEach(function(name) { defCache[name].finalize(); }); }; ```
/content/code_sandbox/node_modules/ast-types/lib/types.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
5,766
```javascript var types = require("./types"); var n = types.namedTypes; var b = types.builders; var isNumber = types.builtInTypes.number; var isArray = types.builtInTypes.array; var Path = require("./path"); var Scope = require("./scope"); function NodePath(value, parentPath, name) { if (!(this instanceof NodePath)) { throw new Error("NodePath constructor cannot be invoked without 'new'"); } Path.call(this, value, parentPath, name); } var NPp = NodePath.prototype = Object.create(Path.prototype, { constructor: { value: NodePath, enumerable: false, writable: true, configurable: true } }); Object.defineProperties(NPp, { node: { get: function() { Object.defineProperty(this, "node", { configurable: true, // Enable deletion. value: this._computeNode() }); return this.node; } }, parent: { get: function() { Object.defineProperty(this, "parent", { configurable: true, // Enable deletion. value: this._computeParent() }); return this.parent; } }, scope: { get: function() { Object.defineProperty(this, "scope", { configurable: true, // Enable deletion. value: this._computeScope() }); return this.scope; } } }); NPp.replace = function() { delete this.node; delete this.parent; delete this.scope; return Path.prototype.replace.apply(this, arguments); }; NPp.prune = function() { var remainingNodePath = this.parent; this.replace(); return cleanUpNodesAfterPrune(remainingNodePath); }; // The value of the first ancestor Path whose value is a Node. NPp._computeNode = function() { var value = this.value; if (n.Node.check(value)) { return value; } var pp = this.parentPath; return pp && pp.node || null; }; // The first ancestor Path whose value is a Node distinct from this.node. NPp._computeParent = function() { var value = this.value; var pp = this.parentPath; if (!n.Node.check(value)) { while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } if (pp) { pp = pp.parentPath; } } while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } return pp || null; }; // The closest enclosing scope that governs this node. NPp._computeScope = function() { var value = this.value; var pp = this.parentPath; var scope = pp && pp.scope; if (n.Node.check(value) && Scope.isEstablishedBy(value)) { scope = new Scope(this, scope); } return scope || null; }; NPp.getValueProperty = function(name) { return types.getFieldValue(this.value, name); }; /** * Determine whether this.node needs to be wrapped in parentheses in order * for a parser to reproduce the same local AST structure. * * For instance, in the expression `(1 + 2) * 3`, the BinaryExpression * whose operator is "+" needs parentheses, because `1 + 2 * 3` would * parse differently. * * If assumeExpressionContext === true, we don't worry about edge cases * like an anonymous FunctionExpression appearing lexically first in its * enclosing statement and thus needing parentheses to avoid being parsed * as a FunctionDeclaration with a missing name. */ NPp.needsParens = function(assumeExpressionContext) { var pp = this.parentPath; if (!pp) { return false; } var node = this.value; // Only expressions need parentheses. if (!n.Expression.check(node)) { return false; } // Identifiers never need parentheses. if (node.type === "Identifier") { return false; } while (!n.Node.check(pp.value)) { pp = pp.parentPath; if (!pp) { return false; } } var parent = pp.value; switch (node.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return parent.type === "MemberExpression" && this.name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": switch (parent.type) { case "CallExpression": return this.name === "callee" && parent.callee === node; case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return true; case "MemberExpression": return this.name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": var po = parent.operator; var pp = PRECEDENCE[po]; var no = node.operator; var np = PRECEDENCE[no]; if (pp > np) { return true; } if (pp === np && this.name === "right") { if (parent.right !== node) { throw new Error("Nodes must be equal"); } return true; } default: return false; } case "SequenceExpression": switch (parent.type) { case "ForStatement": // Although parentheses wouldn't hurt around sequence // expressions in the head of for loops, traditional style // dictates that e.g. i++, j++ should not be wrapped with // parentheses. return false; case "ExpressionStatement": return this.name !== "expression"; default: // Otherwise err on the side of overparenthesization, adding // explicit exceptions above if this proves overzealous. return true; } case "YieldExpression": switch (parent.type) { case "BinaryExpression": case "LogicalExpression": case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "CallExpression": case "MemberExpression": case "NewExpression": case "ConditionalExpression": case "YieldExpression": return true; default: return false; } case "Literal": return parent.type === "MemberExpression" && isNumber.check(node.value) && this.name === "object" && parent.object === node; case "AssignmentExpression": case "ConditionalExpression": switch (parent.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "BinaryExpression": case "LogicalExpression": return true; case "CallExpression": return this.name === "callee" && parent.callee === node; case "ConditionalExpression": return this.name === "test" && parent.test === node; case "MemberExpression": return this.name === "object" && parent.object === node; default: return false; } default: if (parent.type === "NewExpression" && this.name === "callee" && parent.callee === node) { return containsCallExpression(node); } } if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) return true; return false; }; function isBinary(node) { return n.BinaryExpression.check(node) || n.LogicalExpression.check(node); } function isUnaryLike(node) { return n.UnaryExpression.check(node) // I considered making SpreadElement and SpreadProperty subtypes // of UnaryExpression, but they're not really Expression nodes. || (n.SpreadElement && n.SpreadElement.check(node)) || (n.SpreadProperty && n.SpreadProperty.check(node)); } var PRECEDENCE = {}; [["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ].forEach(function(tier, i) { tier.forEach(function(op) { PRECEDENCE[op] = i; }); }); function containsCallExpression(node) { if (n.CallExpression.check(node)) { return true; } if (isArray.check(node)) { return node.some(containsCallExpression); } if (n.Node.check(node)) { return types.someField(node, function(name, child) { return containsCallExpression(child); }); } return false; } NPp.canBeFirstInStatement = function() { var node = this.node; return !n.FunctionExpression.check(node) && !n.ObjectExpression.check(node); }; NPp.firstInStatement = function() { return firstInStatement(this); }; function firstInStatement(path) { for (var node, parent; path.parent; path = path.parent) { node = path.node; parent = path.parent.node; if (n.BlockStatement.check(parent) && path.parent.name === "body" && path.name === 0) { if (parent.body[0] !== node) { throw new Error("Nodes must be equal"); } return true; } if (n.ExpressionStatement.check(parent) && path.name === "expression") { if (parent.expression !== node) { throw new Error("Nodes must be equal"); } return true; } if (n.SequenceExpression.check(parent) && path.parent.name === "expressions" && path.name === 0) { if (parent.expressions[0] !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.CallExpression.check(parent) && path.name === "callee") { if (parent.callee !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.MemberExpression.check(parent) && path.name === "object") { if (parent.object !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.ConditionalExpression.check(parent) && path.name === "test") { if (parent.test !== node) { throw new Error("Nodes must be equal"); } continue; } if (isBinary(parent) && path.name === "left") { if (parent.left !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.UnaryExpression.check(parent) && !parent.prefix && path.name === "argument") { if (parent.argument !== node) { throw new Error("Nodes must be equal"); } continue; } return false; } return true; } /** * Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up. */ function cleanUpNodesAfterPrune(remainingNodePath) { if (n.VariableDeclaration.check(remainingNodePath.node)) { var declarations = remainingNodePath.get('declarations').value; if (!declarations || declarations.length === 0) { return remainingNodePath.prune(); } } else if (n.ExpressionStatement.check(remainingNodePath.node)) { if (!remainingNodePath.get('expression').value) { return remainingNodePath.prune(); } } else if (n.IfStatement.check(remainingNodePath.node)) { cleanUpIfStatementAfterPrune(remainingNodePath); } return remainingNodePath; } function cleanUpIfStatementAfterPrune(ifStatement) { var testExpression = ifStatement.get('test').value; var alternate = ifStatement.get('alternate').value; var consequent = ifStatement.get('consequent').value; if (!consequent && !alternate) { var testExpressionStatement = b.expressionStatement(testExpression); ifStatement.replace(testExpressionStatement); } else if (!consequent && alternate) { var negatedTestExpression = b.unaryExpression('!', testExpression, true); if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') { negatedTestExpression = testExpression.argument; } ifStatement.get("test").replace(negatedTestExpression); ifStatement.get("consequent").replace(alternate); ifStatement.get("alternate").replace(); } } module.exports = NodePath; ```
/content/code_sandbox/node_modules/ast-types/lib/node-path.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,690
```javascript require("./core"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; // Note that none of these types are buildable because the Mozilla Parser // API doesn't specify any builder functions, and nobody uses E4X anymore. def("XMLDefaultDeclaration") .bases("Declaration") .field("namespace", def("Expression")); def("XMLAnyName").bases("Expression"); def("XMLQualifiedIdentifier") .bases("Expression") .field("left", or(def("Identifier"), def("XMLAnyName"))) .field("right", or(def("Identifier"), def("Expression"))) .field("computed", Boolean); def("XMLFunctionQualifiedIdentifier") .bases("Expression") .field("right", or(def("Identifier"), def("Expression"))) .field("computed", Boolean); def("XMLAttributeSelector") .bases("Expression") .field("attribute", def("Expression")); def("XMLFilterExpression") .bases("Expression") .field("left", def("Expression")) .field("right", def("Expression")); def("XMLElement") .bases("XML", "Expression") .field("contents", [def("XML")]); def("XMLList") .bases("XML", "Expression") .field("contents", [def("XML")]); def("XML").bases("Node"); def("XMLEscape") .bases("XML") .field("expression", def("Expression")); def("XMLText") .bases("XML") .field("text", String); def("XMLStartTag") .bases("XML") .field("contents", [def("XML")]); def("XMLEndTag") .bases("XML") .field("contents", [def("XML")]); def("XMLPointTag") .bases("XML") .field("contents", [def("XML")]); def("XMLName") .bases("XML") .field("contents", or(String, [def("XML")])); def("XMLAttribute") .bases("XML") .field("value", String); def("XMLCdata") .bases("XML") .field("contents", String); def("XMLComment") .bases("XML") .field("contents", String); def("XMLProcessingInstruction") .bases("XML") .field("target", String) .field("contents", or(String, null)); ```
/content/code_sandbox/node_modules/ast-types/def/e4x.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
521
```javascript require("./core"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; var shared = require("../lib/shared"); var geq = shared.geq; var defaults = shared.defaults; def("Function") // SpiderMonkey allows expression closures: function(x) x+1 .field("body", or(def("BlockStatement"), def("Expression"))); def("ForInStatement") .build("left", "right", "body", "each") .field("each", Boolean, defaults["false"]); def("ForOfStatement") .bases("Statement") .build("left", "right", "body") .field("left", or( def("VariableDeclaration"), def("Expression"))) .field("right", def("Expression")) .field("body", def("Statement")); def("LetStatement") .bases("Statement") .build("head", "body") // TODO Deviating from the spec by reusing VariableDeclarator here. .field("head", [def("VariableDeclarator")]) .field("body", def("Statement")); def("LetExpression") .bases("Expression") .build("head", "body") // TODO Deviating from the spec by reusing VariableDeclarator here. .field("head", [def("VariableDeclarator")]) .field("body", def("Expression")); def("GraphExpression") .bases("Expression") .build("index", "expression") .field("index", geq(0)) .field("expression", def("Literal")); def("GraphIndexExpression") .bases("Expression") .build("index") .field("index", geq(0)); ```
/content/code_sandbox/node_modules/ast-types/def/mozilla.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
374
```javascript require("./es7"); var types = require("../lib/types"); var defaults = require("../lib/shared").defaults; var def = types.Type.def; var or = types.Type.or; def("Noop") .bases("Node") .build(); def("DoExpression") .bases("Expression") .build("body") .field("body", [def("Statement")]); def("Super") .bases("Expression") .build(); def("BindExpression") .bases("Expression") .build("object", "callee") .field("object", or(def("Expression"), null)) .field("callee", def("Expression")); def("Decorator") .bases("Node") .build("expression") .field("expression", def("Expression")); def("Property") .field("decorators", or([def("Decorator")], null), defaults["null"]); def("MethodDefinition") .field("decorators", or([def("Decorator")], null), defaults["null"]); def("MetaProperty") .bases("Expression") .build("meta", "property") .field("meta", def("Identifier")) .field("property", def("Identifier")); def("ParenthesizedExpression") .bases("Expression") .build("expression") .field("expression", def("Expression")); def("ImportSpecifier") .bases("ModuleSpecifier") .build("imported", "local") .field("imported", def("Identifier")); def("ImportDefaultSpecifier") .bases("ModuleSpecifier") .build("local"); def("ImportNamespaceSpecifier") .bases("ModuleSpecifier") .build("local"); def("ExportDefaultDeclaration") .bases("Declaration") .build("declaration") .field("declaration", or(def("Declaration"), def("Expression"))); def("ExportNamedDeclaration") .bases("Declaration") .build("declaration", "specifiers", "source") .field("declaration", or(def("Declaration"), null)) .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray) .field("source", or(def("Literal"), null), defaults["null"]); def("ExportSpecifier") .bases("ModuleSpecifier") .build("local", "exported") .field("exported", def("Identifier")); def("ExportNamespaceSpecifier") .bases("Specifier") .build("exported") .field("exported", def("Identifier")); def("ExportDefaultSpecifier") .bases("Specifier") .build("exported") .field("exported", def("Identifier")); def("ExportAllDeclaration") .bases("Declaration") .build("exported", "source") .field("exported", or(def("Identifier"), null)) .field("source", def("Literal")); def("CommentBlock") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); def("CommentLine") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); ```
/content/code_sandbox/node_modules/ast-types/def/babel.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
656
```javascript require("./es7"); var types = require("../lib/types"); var defaults = require("../lib/shared").defaults; var def = types.Type.def; var or = types.Type.or; def("VariableDeclaration") .field("declarations", [or( def("VariableDeclarator"), def("Identifier") // Esprima deviation. )]); def("Property") .field("value", or( def("Expression"), def("Pattern") // Esprima deviation. )); def("ArrayPattern") .field("elements", [or( def("Pattern"), def("SpreadElement"), null )]); def("ObjectPattern") .field("properties", [or( def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty") // Used by Esprima. )]); // Like ModuleSpecifier, except type:"ExportSpecifier" and buildable. // export {<id [as name]>} [from ...]; def("ExportSpecifier") .bases("ModuleSpecifier") .build("id", "name"); // export <*> from ...; def("ExportBatchSpecifier") .bases("Specifier") .build(); // Like ModuleSpecifier, except type:"ImportSpecifier" and buildable. // import {<id [as name]>} from ...; def("ImportSpecifier") .bases("ModuleSpecifier") .build("id", "name"); // import <* as id> from ...; def("ImportNamespaceSpecifier") .bases("ModuleSpecifier") .build("id"); // import <id> from ...; def("ImportDefaultSpecifier") .bases("ModuleSpecifier") .build("id"); def("ExportDeclaration") .bases("Declaration") .build("default", "declaration", "specifiers", "source") .field("default", Boolean) .field("declaration", or( def("Declaration"), def("Expression"), // Implies default. null )) .field("specifiers", [or( def("ExportSpecifier"), def("ExportBatchSpecifier") )], defaults.emptyArray) .field("source", or( def("Literal"), null ), defaults["null"]); def("ImportDeclaration") .bases("Declaration") .build("specifiers", "source") .field("specifiers", [or( def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier") )], defaults.emptyArray) .field("source", def("Literal")); def("Block") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); def("Line") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); ```
/content/code_sandbox/node_modules/ast-types/def/esprima.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
597
```javascript require("./es7"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; var defaults = require("../lib/shared").defaults; def("JSXAttribute") .bases("Node") .build("name", "value") .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName"))) .field("value", or( def("Literal"), // attr="value" def("JSXExpressionContainer"), // attr={value} null // attr= or just attr ), defaults["null"]); def("JSXIdentifier") .bases("Identifier") .build("name") .field("name", String); def("JSXNamespacedName") .bases("Node") .build("namespace", "name") .field("namespace", def("JSXIdentifier")) .field("name", def("JSXIdentifier")); def("JSXMemberExpression") .bases("MemberExpression") .build("object", "property") .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression"))) .field("property", def("JSXIdentifier")) .field("computed", Boolean, defaults.false); var JSXElementName = or( def("JSXIdentifier"), def("JSXNamespacedName"), def("JSXMemberExpression") ); def("JSXSpreadAttribute") .bases("Node") .build("argument") .field("argument", def("Expression")); var JSXAttributes = [or( def("JSXAttribute"), def("JSXSpreadAttribute") )]; def("JSXExpressionContainer") .bases("Expression") .build("expression") .field("expression", def("Expression")); def("JSXElement") .bases("Expression") .build("openingElement", "closingElement", "children") .field("openingElement", def("JSXOpeningElement")) .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"]) .field("children", [or( def("JSXElement"), def("JSXExpressionContainer"), def("JSXText"), def("Literal") // TODO Esprima should return JSXText instead. )], defaults.emptyArray) .field("name", JSXElementName, function() { // Little-known fact: the `this` object inside a default function // is none other than the partially-built object itself, and any // fields initialized directly from builder function arguments // (like openingElement, closingElement, and children) are // guaranteed to be available. return this.openingElement.name; }, true) // hidden from traversal .field("selfClosing", Boolean, function() { return this.openingElement.selfClosing; }, true) // hidden from traversal .field("attributes", JSXAttributes, function() { return this.openingElement.attributes; }, true); // hidden from traversal def("JSXOpeningElement") .bases("Node") // TODO Does this make sense? Can't really be an JSXElement. .build("name", "attributes", "selfClosing") .field("name", JSXElementName) .field("attributes", JSXAttributes, defaults.emptyArray) .field("selfClosing", Boolean, defaults["false"]); def("JSXClosingElement") .bases("Node") // TODO Same concern. .build("name") .field("name", JSXElementName); def("JSXText") .bases("Literal") .build("value") .field("value", String); def("JSXEmptyExpression").bases("Expression").build(); // Type Annotations def("Type").bases("Node"); def("AnyTypeAnnotation") .bases("Type") .build(); def("MixedTypeAnnotation") .bases("Type") .build(); def("VoidTypeAnnotation") .bases("Type") .build(); def("NumberTypeAnnotation") .bases("Type") .build(); def("NumberLiteralTypeAnnotation") .bases("Type") .build("value", "raw") .field("value", Number) .field("raw", String); def("StringTypeAnnotation") .bases("Type") .build(); def("StringLiteralTypeAnnotation") .bases("Type") .build("value", "raw") .field("value", String) .field("raw", String); def("BooleanTypeAnnotation") .bases("Type") .build(); def("BooleanLiteralTypeAnnotation") .bases("Type") .build("value", "raw") .field("value", Boolean) .field("raw", String); def("TypeAnnotation") .bases("Node") .build("typeAnnotation") .field("typeAnnotation", def("Type")); def("NullableTypeAnnotation") .bases("Type") .build("typeAnnotation") .field("typeAnnotation", def("Type")); def("FunctionTypeAnnotation") .bases("Type") .build("params", "returnType", "rest", "typeParameters") .field("params", [def("FunctionTypeParam")]) .field("returnType", def("Type")) .field("rest", or(def("FunctionTypeParam"), null)) .field("typeParameters", or(def("TypeParameterDeclaration"), null)); def("FunctionTypeParam") .bases("Node") .build("name", "typeAnnotation", "optional") .field("name", def("Identifier")) .field("typeAnnotation", def("Type")) .field("optional", Boolean); def("ArrayTypeAnnotation") .bases("Type") .build("elementType") .field("elementType", def("Type")); def("ObjectTypeAnnotation") .bases("Type") .build("properties") .field("properties", [def("ObjectTypeProperty")]) .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray) .field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray); def("ObjectTypeProperty") .bases("Node") .build("key", "value", "optional") .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("Type")) .field("optional", Boolean); def("ObjectTypeIndexer") .bases("Node") .build("id", "key", "value") .field("id", def("Identifier")) .field("key", def("Type")) .field("value", def("Type")); def("ObjectTypeCallProperty") .bases("Node") .build("value") .field("value", def("FunctionTypeAnnotation")) .field("static", Boolean, false); def("QualifiedTypeIdentifier") .bases("Node") .build("qualification", "id") .field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier"))) .field("id", def("Identifier")); def("GenericTypeAnnotation") .bases("Type") .build("id", "typeParameters") .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier"))) .field("typeParameters", or(def("TypeParameterInstantiation"), null)); def("MemberTypeAnnotation") .bases("Type") .build("object", "property") .field("object", def("Identifier")) .field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation"))); def("UnionTypeAnnotation") .bases("Type") .build("types") .field("types", [def("Type")]); def("IntersectionTypeAnnotation") .bases("Type") .build("types") .field("types", [def("Type")]); def("TypeofTypeAnnotation") .bases("Type") .build("argument") .field("argument", def("Type")); def("Identifier") .field("typeAnnotation", or(def("TypeAnnotation"), null), defaults["null"]); def("TypeParameterDeclaration") .bases("Node") .build("params") .field("params", [def("Identifier")]); def("TypeParameterInstantiation") .bases("Node") .build("params") .field("params", [def("Type")]); def("Function") .field("returnType", or(def("TypeAnnotation"), null), defaults["null"]) .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]); def("ClassProperty") .build("key", "value", "typeAnnotation", "static") .field("value", or(def("Expression"), null)) .field("typeAnnotation", or(def("TypeAnnotation"), null)) .field("static", Boolean, defaults["false"]); def("ClassImplements") .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]); def("InterfaceDeclaration") .bases("Statement") .build("id", "body", "extends") .field("id", def("Identifier")) .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]) .field("body", def("ObjectTypeAnnotation")) .field("extends", [def("InterfaceExtends")]); def("InterfaceExtends") .bases("Node") .build("id") .field("id", def("Identifier")) .field("typeParameters", or(def("TypeParameterInstantiation"), null)); def("TypeAlias") .bases("Declaration") .build("id", "typeParameters", "right") .field("id", def("Identifier")) .field("typeParameters", or(def("TypeParameterDeclaration"), null)) .field("right", def("Type")); def("TypeCastExpression") .bases("Expression") .build("expression", "typeAnnotation") .field("expression", def("Expression")) .field("typeAnnotation", def("TypeAnnotation")); def("TupleTypeAnnotation") .bases("Type") .build("types") .field("types", [def("Type")]); def("DeclareVariable") .bases("Statement") .build("id") .field("id", def("Identifier")); def("DeclareFunction") .bases("Statement") .build("id") .field("id", def("Identifier")); def("DeclareClass") .bases("InterfaceDeclaration") .build("id"); def("DeclareModule") .bases("Statement") .build("id", "body") .field("id", or(def("Identifier"), def("Literal"))) .field("body", def("BlockStatement")); def("DeclareExportDeclaration") .bases("Declaration") .build("default", "declaration", "specifiers", "source") .field("default", Boolean) .field("declaration", or( def("DeclareVariable"), def("DeclareFunction"), def("DeclareClass"), def("Type"), // Implies default. null )) .field("specifiers", [or( def("ExportSpecifier"), def("ExportBatchSpecifier") )], defaults.emptyArray) .field("source", or( def("Literal"), null ), defaults["null"]); ```
/content/code_sandbox/node_modules/ast-types/def/fb-harmony.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,434
```javascript require("./es6"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; var builtin = types.builtInTypes; var defaults = require("../lib/shared").defaults; def("Function") .field("async", Boolean, defaults["false"]); def("SpreadProperty") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ObjectExpression") .field("properties", [or(def("Property"), def("SpreadProperty"))]); def("SpreadPropertyPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("ObjectPattern") .field("properties", [or( def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern") )]); def("AwaitExpression") .bases("Expression") .build("argument", "all") .field("argument", or(def("Expression"), null)) .field("all", Boolean, defaults["false"]); ```
/content/code_sandbox/node_modules/ast-types/def/es7.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
221
```javascript var types = require("../lib/types"); var Type = types.Type; var def = Type.def; var or = Type.or; var shared = require("../lib/shared"); var defaults = shared.defaults; var geq = shared.geq; // Abstract supertype of all syntactic entities that are allowed to have a // .loc field. def("Printable") .field("loc", or( def("SourceLocation"), null ), defaults["null"], true); def("Node") .bases("Printable") .field("type", String) .field("comments", or( [def("Comment")], null ), defaults["null"], true); def("SourceLocation") .build("start", "end", "source") .field("start", def("Position")) .field("end", def("Position")) .field("source", or(String, null), defaults["null"]); def("Position") .build("line", "column") .field("line", geq(1)) .field("column", geq(0)); def("File") .bases("Node") .build("program") .field("program", def("Program")); def("Program") .bases("Node") .build("body") .field("body", [def("Statement")]); def("Function") .bases("Node") .field("id", or(def("Identifier"), null), defaults["null"]) .field("params", [def("Pattern")]) .field("body", def("BlockStatement")); def("Statement").bases("Node"); // The empty .build() here means that an EmptyStatement can be constructed // (i.e. it's not abstract) but that it needs no arguments. def("EmptyStatement").bases("Statement").build(); def("BlockStatement") .bases("Statement") .build("body") .field("body", [def("Statement")]); // TODO Figure out how to silently coerce Expressions to // ExpressionStatements where a Statement was expected. def("ExpressionStatement") .bases("Statement") .build("expression") .field("expression", def("Expression")); def("IfStatement") .bases("Statement") .build("test", "consequent", "alternate") .field("test", def("Expression")) .field("consequent", def("Statement")) .field("alternate", or(def("Statement"), null), defaults["null"]); def("LabeledStatement") .bases("Statement") .build("label", "body") .field("label", def("Identifier")) .field("body", def("Statement")); def("BreakStatement") .bases("Statement") .build("label") .field("label", or(def("Identifier"), null), defaults["null"]); def("ContinueStatement") .bases("Statement") .build("label") .field("label", or(def("Identifier"), null), defaults["null"]); def("WithStatement") .bases("Statement") .build("object", "body") .field("object", def("Expression")) .field("body", def("Statement")); def("SwitchStatement") .bases("Statement") .build("discriminant", "cases", "lexical") .field("discriminant", def("Expression")) .field("cases", [def("SwitchCase")]) .field("lexical", Boolean, defaults["false"]); def("ReturnStatement") .bases("Statement") .build("argument") .field("argument", or(def("Expression"), null)); def("ThrowStatement") .bases("Statement") .build("argument") .field("argument", def("Expression")); def("TryStatement") .bases("Statement") .build("block", "handler", "finalizer") .field("block", def("BlockStatement")) .field("handler", or(def("CatchClause"), null), function() { return this.handlers && this.handlers[0] || null; }) .field("handlers", [def("CatchClause")], function() { return this.handler ? [this.handler] : []; }, true) // Indicates this field is hidden from eachField iteration. .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray) .field("finalizer", or(def("BlockStatement"), null), defaults["null"]); def("CatchClause") .bases("Node") .build("param", "guard", "body") .field("param", def("Pattern")) .field("guard", or(def("Expression"), null), defaults["null"]) .field("body", def("BlockStatement")); def("WhileStatement") .bases("Statement") .build("test", "body") .field("test", def("Expression")) .field("body", def("Statement")); def("DoWhileStatement") .bases("Statement") .build("body", "test") .field("body", def("Statement")) .field("test", def("Expression")); def("ForStatement") .bases("Statement") .build("init", "test", "update", "body") .field("init", or( def("VariableDeclaration"), def("Expression"), null)) .field("test", or(def("Expression"), null)) .field("update", or(def("Expression"), null)) .field("body", def("Statement")); def("ForInStatement") .bases("Statement") .build("left", "right", "body") .field("left", or( def("VariableDeclaration"), def("Expression"))) .field("right", def("Expression")) .field("body", def("Statement")); def("DebuggerStatement").bases("Statement").build(); def("Declaration").bases("Statement"); def("FunctionDeclaration") .bases("Function", "Declaration") .build("id", "params", "body") .field("id", def("Identifier")); def("FunctionExpression") .bases("Function", "Expression") .build("id", "params", "body"); def("VariableDeclaration") .bases("Declaration") .build("kind", "declarations") .field("kind", or("var", "let", "const")) .field("declarations", [def("VariableDeclarator")]); def("VariableDeclarator") .bases("Node") .build("id", "init") .field("id", def("Pattern")) .field("init", or(def("Expression"), null)); // TODO Are all Expressions really Patterns? def("Expression").bases("Node", "Pattern"); def("ThisExpression").bases("Expression").build(); def("ArrayExpression") .bases("Expression") .build("elements") .field("elements", [or(def("Expression"), null)]); def("ObjectExpression") .bases("Expression") .build("properties") .field("properties", [def("Property")]); // TODO Not in the Mozilla Parser API, but used by Esprima. def("Property") .bases("Node") // Want to be able to visit Property Nodes. .build("kind", "key", "value") .field("kind", or("init", "get", "set")) .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("Expression")); def("SequenceExpression") .bases("Expression") .build("expressions") .field("expressions", [def("Expression")]); var UnaryOperator = or( "-", "+", "!", "~", "typeof", "void", "delete"); def("UnaryExpression") .bases("Expression") .build("operator", "argument", "prefix") .field("operator", UnaryOperator) .field("argument", def("Expression")) // Esprima doesn't bother with this field, presumably because it's // always true for unary operators. .field("prefix", Boolean, defaults["true"]); var BinaryOperator = or( "==", "!=", "===", "!==", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "&", // TODO Missing from the Parser API. "|", "^", "in", "instanceof", ".."); def("BinaryExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", BinaryOperator) .field("left", def("Expression")) .field("right", def("Expression")); var AssignmentOperator = or( "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="); def("AssignmentExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", AssignmentOperator) .field("left", def("Pattern")) .field("right", def("Expression")); var UpdateOperator = or("++", "--"); def("UpdateExpression") .bases("Expression") .build("operator", "argument", "prefix") .field("operator", UpdateOperator) .field("argument", def("Expression")) .field("prefix", Boolean); var LogicalOperator = or("||", "&&"); def("LogicalExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", LogicalOperator) .field("left", def("Expression")) .field("right", def("Expression")); def("ConditionalExpression") .bases("Expression") .build("test", "consequent", "alternate") .field("test", def("Expression")) .field("consequent", def("Expression")) .field("alternate", def("Expression")); def("NewExpression") .bases("Expression") .build("callee", "arguments") .field("callee", def("Expression")) // The Mozilla Parser API gives this type as [or(def("Expression"), // null)], but null values don't really make sense at the call site. // TODO Report this nonsense. .field("arguments", [def("Expression")]); def("CallExpression") .bases("Expression") .build("callee", "arguments") .field("callee", def("Expression")) // See comment for NewExpression above. .field("arguments", [def("Expression")]); def("MemberExpression") .bases("Expression") .build("object", "property", "computed") .field("object", def("Expression")) .field("property", or(def("Identifier"), def("Expression"))) .field("computed", Boolean, function(){ var type = this.property.type; if (type === 'Literal' || type === 'MemberExpression' || type === 'BinaryExpression') { return true; } return false; }); def("Pattern").bases("Node"); def("SwitchCase") .bases("Node") .build("test", "consequent") .field("test", or(def("Expression"), null)) .field("consequent", [def("Statement")]); def("Identifier") // But aren't Expressions and Patterns already Nodes? TODO Report this. .bases("Node", "Expression", "Pattern") .build("name") .field("name", String); def("Literal") // But aren't Expressions already Nodes? TODO Report this. .bases("Node", "Expression") .build("value") .field("value", or(String, Boolean, null, Number, RegExp)) .field("regex", or({ pattern: String, flags: String }, null), function() { if (this.value instanceof RegExp) { var flags = ""; if (this.value.ignoreCase) flags += "i"; if (this.value.multiline) flags += "m"; if (this.value.global) flags += "g"; return { pattern: this.value.source, flags: flags }; } return null; }); // Abstract (non-buildable) comment supertype. Not a Node. def("Comment") .bases("Printable") .field("value", String) // A .leading comment comes before the node, whereas a .trailing // comment comes after it. These two fields should not both be true, // but they might both be false when the comment falls inside a node // and the node has no children for the comment to lead or trail, // e.g. { /*dangling*/ }. .field("leading", Boolean, defaults["true"]) .field("trailing", Boolean, defaults["false"]); ```
/content/code_sandbox/node_modules/ast-types/def/core.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,737
```javascript module.exports = parse; //following path_to_url#nth-child-pseudo //[ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? var re_nthElement = /^([+\-]?\d*n)?\s*(?:([+\-]?)\s*(\d+))?$/; /* parses a nth-check formula, returns an array of two numbers */ function parse(formula){ formula = formula.trim().toLowerCase(); if(formula === "even"){ return [2, 0]; } else if(formula === "odd"){ return [2, 1]; } else { var parsed = formula.match(re_nthElement); if(!parsed){ throw new SyntaxError("n-th rule couldn't be parsed ('" + formula + "')"); } var a; if(parsed[1]){ a = parseInt(parsed[1], 10); if(isNaN(a)){ if(parsed[1].charAt(0) === "-") a = -1; else a = 1; } } else a = 0; return [ a, parsed[3] ? parseInt((parsed[2] || "") + parsed[3], 10) : 0 ]; } } ```
/content/code_sandbox/node_modules/nth-check/parse.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
282
```javascript var parse = require("./parse.js"), compile = require("./compile.js"); module.exports = function nthCheck(formula){ return compile(parse(formula)); }; module.exports.parse = parse; module.exports.compile = compile; ```
/content/code_sandbox/node_modules/nth-check/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
45
```javascript module.exports = compile; var BaseFuncs = require("boolbase"), trueFunc = BaseFuncs.trueFunc, falseFunc = BaseFuncs.falseFunc; /* returns a function that checks if an elements index matches the given rule highly optimized to return the fastest solution */ function compile(parsed){ var a = parsed[0], b = parsed[1] - 1; //when b <= 0, a*n won't be possible for any matches when a < 0 //besides, the specification says that no element is matched when a and b are 0 if(b < 0 && a <= 0) return falseFunc; //when a is in the range -1..1, it matches any element (so only b is checked) if(a ===-1) return function(pos){ return pos <= b; }; if(a === 0) return function(pos){ return pos === b; }; //when b <= 0 and a === 1, they match any element if(a === 1) return b < 0 ? trueFunc : function(pos){ return pos >= b; }; //when a > 0, modulo can be used to check if there is a match var bMod = b % a; if(bMod < 0) bMod += a; if(a > 1){ return function(pos){ return pos >= b && pos % a === bMod; }; } a *= -1; //make `a` positive return function(pos){ return pos <= b && pos % a === bMod; }; } ```
/content/code_sandbox/node_modules/nth-check/compile.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
344
```javascript module.exports = { trueFunc: function trueFunc(){ return true; }, falseFunc: function falseFunc(){ return false; } }; ```
/content/code_sandbox/node_modules/boolbase/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
32
```javascript require("./core"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; var defaults = require("../lib/shared").defaults; def("Function") .field("generator", Boolean, defaults["false"]) .field("expression", Boolean, defaults["false"]) .field("defaults", [or(def("Expression"), null)], defaults.emptyArray) // TODO This could be represented as a RestElement in .params. .field("rest", or(def("Identifier"), null), defaults["null"]); // The ESTree way of representing a ...rest parameter. def("RestElement") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("SpreadElementPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("FunctionDeclaration") .build("id", "params", "body", "generator", "expression"); def("FunctionExpression") .build("id", "params", "body", "generator", "expression"); // The Parser API calls this ArrowExpression, but Esprima and all other // actual parsers use ArrowFunctionExpression. def("ArrowFunctionExpression") .bases("Function", "Expression") .build("params", "body", "expression") // The forced null value here is compatible with the overridden // definition of the "id" field in the Function interface. .field("id", null, defaults["null"]) // Arrow function bodies are allowed to be expressions. .field("body", or(def("BlockStatement"), def("Expression"))) // The current spec forbids arrow generators, so I have taken the // liberty of enforcing that. TODO Report this. .field("generator", false, defaults["false"]); def("YieldExpression") .bases("Expression") .build("argument", "delegate") .field("argument", or(def("Expression"), null)) .field("delegate", Boolean, defaults["false"]); def("GeneratorExpression") .bases("Expression") .build("body", "blocks", "filter") .field("body", def("Expression")) .field("blocks", [def("ComprehensionBlock")]) .field("filter", or(def("Expression"), null)); def("ComprehensionExpression") .bases("Expression") .build("body", "blocks", "filter") .field("body", def("Expression")) .field("blocks", [def("ComprehensionBlock")]) .field("filter", or(def("Expression"), null)); def("ComprehensionBlock") .bases("Node") .build("left", "right", "each") .field("left", def("Pattern")) .field("right", def("Expression")) .field("each", Boolean); def("Property") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("value", or(def("Expression"), def("Pattern"))) .field("method", Boolean, defaults["false"]) .field("shorthand", Boolean, defaults["false"]) .field("computed", Boolean, defaults["false"]); def("PropertyPattern") .bases("Pattern") .build("key", "pattern") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("pattern", def("Pattern")) .field("computed", Boolean, defaults["false"]); def("ObjectPattern") .bases("Pattern") .build("properties") .field("properties", [or(def("PropertyPattern"), def("Property"))]); def("ArrayPattern") .bases("Pattern") .build("elements") .field("elements", [or(def("Pattern"), null)]); def("MethodDefinition") .bases("Declaration") .build("kind", "key", "value", "static") .field("kind", or("constructor", "method", "get", "set")) .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("value", def("Function")) .field("computed", Boolean, defaults["false"]) .field("static", Boolean, defaults["false"]); def("SpreadElement") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ArrayExpression") .field("elements", [or( def("Expression"), def("SpreadElement"), def("RestElement"), null )]); def("NewExpression") .field("arguments", [or(def("Expression"), def("SpreadElement"))]); def("CallExpression") .field("arguments", [or(def("Expression"), def("SpreadElement"))]); // Note: this node type is *not* an AssignmentExpression with a Pattern on // the left-hand side! The existing AssignmentExpression type already // supports destructuring assignments. AssignmentPattern nodes may appear // wherever a Pattern is allowed, and the right-hand side represents a // default value to be destructured against the left-hand side, if no // value is otherwise provided. For example: default parameter values. def("AssignmentPattern") .bases("Pattern") .build("left", "right") .field("left", def("Pattern")) .field("right", def("Expression")); var ClassBodyElement = or( def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty") ); def("ClassProperty") .bases("Declaration") .build("key") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("computed", Boolean, defaults["false"]); def("ClassPropertyDefinition") // static property .bases("Declaration") .build("definition") // Yes, Virginia, circular definitions are permitted. .field("definition", ClassBodyElement); def("ClassBody") .bases("Declaration") .build("body") .field("body", [ClassBodyElement]); def("ClassDeclaration") .bases("Declaration") .build("id", "body", "superClass") .field("id", or(def("Identifier"), null)) .field("body", def("ClassBody")) .field("superClass", or(def("Expression"), null), defaults["null"]); def("ClassExpression") .bases("Expression") .build("id", "body", "superClass") .field("id", or(def("Identifier"), null), defaults["null"]) .field("body", def("ClassBody")) .field("superClass", or(def("Expression"), null), defaults["null"]) .field("implements", [def("ClassImplements")], defaults.emptyArray); def("ClassImplements") .bases("Node") .build("id") .field("id", def("Identifier")) .field("superClass", or(def("Expression"), null), defaults["null"]); // Specifier and ModuleSpecifier are abstract non-standard types // introduced for definitional convenience. def("Specifier").bases("Node"); // This supertype is shared/abused by both def/babel.js and // def/esprima.js. In the future, it will be possible to load only one set // of definitions appropriate for a given parser, but until then we must // rely on default functions to reconcile the conflicting AST formats. def("ModuleSpecifier") .bases("Specifier") // This local field is used by Babel/Acorn. It should not technically // be optional in the Babel/Acorn AST format, but it must be optional // in the Esprima AST format. .field("local", or(def("Identifier"), null), defaults["null"]) // The id and name fields are used by Esprima. The id field should not // technically be optional in the Esprima AST format, but it must be // optional in the Babel/Acorn AST format. .field("id", or(def("Identifier"), null), defaults["null"]) .field("name", or(def("Identifier"), null), defaults["null"]); def("TaggedTemplateExpression") .bases("Expression") .build("tag", "quasi") .field("tag", def("Expression")) .field("quasi", def("TemplateLiteral")); def("TemplateLiteral") .bases("Expression") .build("quasis", "expressions") .field("quasis", [def("TemplateElement")]) .field("expressions", [def("Expression")]); def("TemplateElement") .bases("Node") .build("value", "tail") .field("value", {"cooked": String, "raw": String}) .field("tail", Boolean); ```
/content/code_sandbox/node_modules/ast-types/def/es6.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,889
```javascript #!/usr/bin/env node /* 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 sloppy:true plusplus:true node:true rhino:true */ /*global phantom:true */ var fs, system, esprima, options, fnames, forceFile, count; if (typeof esprima === 'undefined') { // PhantomJS can only require() relative files if (typeof phantom === 'object') { fs = require('fs'); system = require('system'); esprima = require('./esprima'); } else if (typeof require === 'function') { fs = require('fs'); try { esprima = require('esprima'); } catch (e) { esprima = require('../'); } } else if (typeof load === 'function') { try { load('esprima.js'); } catch (e) { load('../esprima.js'); } } } // Shims to Node.js objects when running under PhantomJS 1.7+. if (typeof phantom === 'object') { fs.readFileSync = fs.read; process = { argv: [].slice.call(system.args), exit: phantom.exit, on: function (evt, callback) { callback(); } }; process.argv.unshift('phantomjs'); } // Shims to Node.js objects when running under Rhino. if (typeof console === 'undefined' && typeof process === 'undefined') { console = { log: print }; fs = { readFileSync: readFile }; process = { argv: arguments, exit: quit, on: function (evt, callback) { callback(); } }; process.argv.unshift('esvalidate.js'); process.argv.unshift('rhino'); } function showUsage() { console.log('Usage:'); console.log(' esvalidate [options] [file.js...]'); console.log(); console.log('Available options:'); console.log(); console.log(' --format=type Set the report format, plain (default) or junit'); console.log(' -v, --version Print program version'); console.log(); process.exit(1); } options = { format: 'plain' }; fnames = []; process.argv.splice(2).forEach(function (entry) { if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { fnames.push(entry); } else if (entry === '-h' || entry === '--help') { showUsage(); } else if (entry === '-v' || entry === '--version') { console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); console.log(); process.exit(0); } else if (entry.slice(0, 9) === '--format=') { options.format = entry.slice(9); if (options.format !== 'plain' && options.format !== 'junit') { console.log('Error: unknown report format ' + options.format + '.'); process.exit(1); } } else if (entry === '--') { forceFile = true; } else { console.log('Error: unknown option ' + entry + '.'); process.exit(1); } }); if (fnames.length === 0) { fnames.push(''); } if (options.format === 'junit') { console.log('<?xml version="1.0" encoding="UTF-8"?>'); console.log('<testsuites>'); } count = 0; function run(fname, content) { var timestamp, syntax, name; try { if (typeof content !== 'string') { throw content; } if (content[0] === '#' && content[1] === '!') { content = '//' + content.substr(2, content.length); } timestamp = Date.now(); syntax = esprima.parse(content, { tolerant: true }); if (options.format === 'junit') { name = fname; if (name.lastIndexOf('/') >= 0) { name = name.slice(name.lastIndexOf('/') + 1); } console.log('<testsuite name="' + fname + '" errors="0" ' + ' failures="' + syntax.errors.length + '" ' + ' tests="' + syntax.errors.length + '" ' + ' time="' + Math.round((Date.now() - timestamp) / 1000) + '">'); syntax.errors.forEach(function (error) { var msg = error.message; msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' + ' time="0">'); console.log(' <error type="SyntaxError" message="' + error.message + '">' + error.message + '(' + name + ':' + error.lineNumber + ')' + '</error>'); console.log(' </testcase>'); }); console.log('</testsuite>'); } else if (options.format === 'plain') { syntax.errors.forEach(function (error) { var msg = error.message; msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); msg = fname + ':' + error.lineNumber + ': ' + msg; console.log(msg); ++count; }); } } catch (e) { ++count; if (options.format === 'junit') { console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' + ' time="' + Math.round((Date.now() - timestamp) / 1000) + '">'); console.log(' <testcase name="' + e.message + '" ' + ' time="0">'); console.log(' <error type="ParseError" message="' + e.message + '">' + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + ')</error>'); console.log(' </testcase>'); console.log('</testsuite>'); } else { console.log(fname + ':' + e.lineNumber + ': ' + e.message.replace(/^Line\ [0-9]*\:\ /, '')); } } } fnames.forEach(function (fname) { var content = ''; try { if (fname && (fname !== '-' || forceFile)) { content = fs.readFileSync(fname, 'utf-8'); } else { fname = ''; process.stdin.resume(); process.stdin.on('data', function(chunk) { content += chunk; }); process.stdin.on('end', function() { run(fname, content); }); return; } } catch (e) { content = e; } run(fname, content); }); process.on('exit', function () { if (options.format === 'junit') { console.log('</testsuites>'); } if (count > 0) { process.exit(1); } if (count === 0 && typeof phantom === 'object') { process.exit(0); } }); ```
/content/code_sandbox/node_modules/esprima/bin/esvalidate.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,775
```javascript #!/usr/bin/env node /* 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 sloppy:true node:true rhino:true */ var fs, esprima, fname, forceFile, content, options, syntax; if (typeof require === 'function') { fs = require('fs'); try { esprima = require('esprima'); } catch (e) { esprima = require('../'); } } else if (typeof load === 'function') { try { load('esprima.js'); } catch (e) { load('../esprima.js'); } } // Shims to Node.js objects when running under Rhino. if (typeof console === 'undefined' && typeof process === 'undefined') { console = { log: print }; fs = { readFileSync: readFile }; process = { argv: arguments, exit: quit }; process.argv.unshift('esparse.js'); process.argv.unshift('rhino'); } function showUsage() { console.log('Usage:'); console.log(' esparse [options] [file.js]'); console.log(); console.log('Available options:'); console.log(); console.log(' --comment Gather all line and block comments in an array'); console.log(' --loc Include line-column location info for each syntax node'); console.log(' --range Include index-based range for each syntax node'); console.log(' --raw Display the raw value of literals'); console.log(' --tokens List all tokens in an array'); console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); console.log(' -v, --version Shows program version'); console.log(); process.exit(1); } options = {}; process.argv.splice(2).forEach(function (entry) { if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { if (typeof fname === 'string') { console.log('Error: more than one input file.'); process.exit(1); } else { fname = entry; } } else if (entry === '-h' || entry === '--help') { showUsage(); } else if (entry === '-v' || entry === '--version') { console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); console.log(); process.exit(0); } else if (entry === '--comment') { options.comment = true; } else if (entry === '--loc') { options.loc = true; } else if (entry === '--range') { options.range = true; } else if (entry === '--raw') { options.raw = true; } else if (entry === '--tokens') { options.tokens = true; } else if (entry === '--tolerant') { options.tolerant = true; } else if (entry === '--') { forceFile = true; } else { console.log('Error: unknown option ' + entry + '.'); process.exit(1); } }); // Special handling for regular expression literal since we need to // convert it to a string literal, otherwise it will be decoded // as object "{}" and the regular expression would be lost. function adjustRegexLiteral(key, value) { if (key === 'value' && value instanceof RegExp) { value = value.toString(); } return value; } function run(content) { syntax = esprima.parse(content, options); console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); } try { if (fname && (fname !== '-' || forceFile)) { run(fs.readFileSync(fname, 'utf-8')); } else { var content = ''; process.stdin.resume(); process.stdin.on('data', function(chunk) { content += chunk; }); process.stdin.on('end', function() { run(content); }); } } catch (e) { console.log('Error: ' + e.message); process.exit(1); } ```
/content/code_sandbox/node_modules/esprima/bin/esparse.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,121
```javascript var crypto = require("crypto"); var BigInteger = require("jsbn").BigInteger; var ECPointFp = require("./lib/ec.js").ECPointFp; var Buffer = require("safer-buffer").Buffer; exports.ECCurves = require("./lib/sec.js"); // zero prepad function unstupid(hex,len) { return (hex.length >= len) ? hex : unstupid("0"+hex,len); } exports.ECKey = function(curve, key, isPublic) { var priv; var c = curve(); var n = c.getN(); var bytes = Math.floor(n.bitLength()/8); if(key) { if(isPublic) { var curve = c.getCurve(); // var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format // var y = key.slice(bytes+1); // this.P = new ECPointFp(curve, // curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), // curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); this.P = curve.decodePointHex(key.toString("hex")); }else{ if(key.length != bytes) return false; priv = new BigInteger(key.toString("hex"), 16); } }else{ var n1 = n.subtract(BigInteger.ONE); var r = new BigInteger(crypto.randomBytes(n.bitLength())); priv = r.mod(n1).add(BigInteger.ONE); this.P = c.getG().multiply(priv); } if(this.P) { // var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); // this.PublicKey = Buffer.from("04"+pubhex,"hex"); this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); } if(priv) { this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); this.deriveSharedSecret = function(key) { if(!key || !key.P) return false; var S = key.P.multiply(priv); return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); } } } ```
/content/code_sandbox/node_modules/ecc-jsbn/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
500
```javascript var ecc = require("./index.js"); var key1 = new ecc.ECKey(ecc.ECCurves.secp160r1); var key2 = new ecc.ECKey(ecc.ECCurves.secp160r1); console.log(key1.deriveSharedSecret(key2)); var key3 = new ecc.ECKey(ecc.ECCurves.secp160r1,key1.PrivateKey); var key4 = new ecc.ECKey(ecc.ECCurves.secp160r1,key2.PublicKey,true); console.log(key3.deriveSharedSecret(key4)); var key1 = new ecc.ECKey(ecc.ECCurves.secp256r1); var key2 = new ecc.ECKey(ecc.ECCurves.secp256r1); console.log(key1.deriveSharedSecret(key2)); var key3 = new ecc.ECKey(ecc.ECCurves.secp256r1,key1.PrivateKey); var key4 = new ecc.ECKey(ecc.ECCurves.secp256r1,key2.PublicKey,true); console.log(key3.deriveSharedSecret(key4)); ```
/content/code_sandbox/node_modules/ecc-jsbn/test.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
239
```javascript // Basic Javascript Elliptic Curve implementation // Ported loosely from BouncyCastle's Java EC code // Only Fp curves implemented for now // Requires jsbn.js and jsbn2.js var BigInteger = require('jsbn').BigInteger var Barrett = BigInteger.prototype.Barrett // ---------------- // ECFieldElementFp // constructor function ECFieldElementFp(q,x) { this.x = x; // TODO if(x.compareTo(q) >= 0) error this.q = q; } function feFpEquals(other) { if(other == this) return true; return (this.q.equals(other.q) && this.x.equals(other.x)); } function feFpToBigInteger() { return this.x; } function feFpNegate() { return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); } function feFpAdd(b) { return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); } function feFpSubtract(b) { return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); } function feFpMultiply(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); } function feFpSquare() { return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); } function feFpDivide(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); } ECFieldElementFp.prototype.equals = feFpEquals; ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; ECFieldElementFp.prototype.negate = feFpNegate; ECFieldElementFp.prototype.add = feFpAdd; ECFieldElementFp.prototype.subtract = feFpSubtract; ECFieldElementFp.prototype.multiply = feFpMultiply; ECFieldElementFp.prototype.square = feFpSquare; ECFieldElementFp.prototype.divide = feFpDivide; // ---------------- // ECPointFp // constructor function ECPointFp(curve,x,y,z) { this.curve = curve; this.x = x; this.y = y; // Projective coordinates: either zinv == null or z * zinv == 1 // z and zinv are just BigIntegers, not fieldElements if(z == null) { this.z = BigInteger.ONE; } else { this.z = z; } this.zinv = null; //TODO: compression flag } function pointFpGetX() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.x.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpGetY() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.y.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpEquals(other) { if(other == this) return true; if(this.isInfinity()) return other.isInfinity(); if(other.isInfinity()) return this.isInfinity(); var u, v; // u = Y2 * Z1 - Y1 * Z2 u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); if(!u.equals(BigInteger.ZERO)) return false; // v = X2 * Z1 - X1 * Z2 v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); return v.equals(BigInteger.ZERO); } function pointFpIsInfinity() { if((this.x == null) && (this.y == null)) return true; return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); } function pointFpNegate() { return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); } function pointFpAdd(b) { if(this.isInfinity()) return b; if(b.isInfinity()) return this; // u = Y2 * Z1 - Y1 * Z2 var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); // v = X2 * Z1 - X1 * Z2 var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); if(BigInteger.ZERO.equals(v)) { if(BigInteger.ZERO.equals(u)) { return this.twice(); // this == b, so double } return this.curve.getInfinity(); // this = -b, so infinity } var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var x2 = b.x.toBigInteger(); var y2 = b.y.toBigInteger(); var v2 = v.square(); var v3 = v2.multiply(v); var x1v2 = x1.multiply(v2); var zu2 = u.square().multiply(this.z); // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); // z3 = v^3 * z1 * z2 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } function pointFpTwice() { if(this.isInfinity()) return this; if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); // TODO: optimized handling of constants var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var y1z1 = y1.multiply(this.z); var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); var a = this.curve.a.toBigInteger(); // w = 3 * x1^2 + a * z1^2 var w = x1.square().multiply(THREE); if(!BigInteger.ZERO.equals(a)) { w = w.add(this.z.square().multiply(a)); } w = w.mod(this.curve.q); //this.curve.reduce(w); // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); // z3 = 8 * (y1 * z1)^3 var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } // Simple NAF (Non-Adjacent Form) multiplication algorithm // TODO: modularize the multiplication algorithm function pointFpMultiply(k) { if(this.isInfinity()) return this; if(k.signum() == 0) return this.curve.getInfinity(); var e = k; var h = e.multiply(new BigInteger("3")); var neg = this.negate(); var R = this; var i; for(i = h.bitLength() - 2; i > 0; --i) { R = R.twice(); var hBit = h.testBit(i); var eBit = e.testBit(i); if (hBit != eBit) { R = R.add(hBit ? this : neg); } } return R; } // Compute this*j + x*k (simultaneous multiplication) function pointFpMultiplyTwo(j,x,k) { var i; if(j.bitLength() > k.bitLength()) i = j.bitLength() - 1; else i = k.bitLength() - 1; var R = this.curve.getInfinity(); var both = this.add(x); while(i >= 0) { R = R.twice(); if(j.testBit(i)) { if(k.testBit(i)) { R = R.add(both); } else { R = R.add(this); } } else { if(k.testBit(i)) { R = R.add(x); } } --i; } return R; } ECPointFp.prototype.getX = pointFpGetX; ECPointFp.prototype.getY = pointFpGetY; ECPointFp.prototype.equals = pointFpEquals; ECPointFp.prototype.isInfinity = pointFpIsInfinity; ECPointFp.prototype.negate = pointFpNegate; ECPointFp.prototype.add = pointFpAdd; ECPointFp.prototype.twice = pointFpTwice; ECPointFp.prototype.multiply = pointFpMultiply; ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; // ---------------- // ECCurveFp // constructor function ECCurveFp(q,a,b) { this.q = q; this.a = this.fromBigInteger(a); this.b = this.fromBigInteger(b); this.infinity = new ECPointFp(this, null, null); this.reducer = new Barrett(this.q); } function curveFpGetQ() { return this.q; } function curveFpGetA() { return this.a; } function curveFpGetB() { return this.b; } function curveFpEquals(other) { if(other == this) return true; return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); } function curveFpGetInfinity() { return this.infinity; } function curveFpFromBigInteger(x) { return new ECFieldElementFp(this.q, x); } function curveReduce(x) { this.reducer.reduce(x); } // for now, work with hex strings because they're easier in JS function curveFpDecodePointHex(s) { switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: case 3: // point compression not supported yet return null; case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } function curveFpEncodePointHex(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var yHex = p.getY().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) { xHex = "0" + xHex; } while (yHex.length < oLen) { yHex = "0" + yHex; } return "04" + xHex + yHex; } ECCurveFp.prototype.getQ = curveFpGetQ; ECCurveFp.prototype.getA = curveFpGetA; ECCurveFp.prototype.getB = curveFpGetB; ECCurveFp.prototype.equals = curveFpEquals; ECCurveFp.prototype.getInfinity = curveFpGetInfinity; ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; ECCurveFp.prototype.reduce = curveReduce; //ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; // from: path_to_url ECCurveFp.prototype.decodePointHex = function(s) { var yIsEven; switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: yIsEven = false; case 3: if(yIsEven == undefined) yIsEven = true; var len = s.length - 2; var xHex = s.substr(2, len); var x = this.fromBigInteger(new BigInteger(xHex,16)); var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); var beta = alpha.sqrt(); if (beta == null) throw "Invalid point compression"; var betaValue = beta.toBigInteger(); if (betaValue.testBit(0) != yIsEven) { // Use the other root beta = this.fromBigInteger(this.getQ().subtract(betaValue)); } return new ECPointFp(this,x,beta); case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } ECCurveFp.prototype.encodeCompressedPointHex = function(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) xHex = "0" + xHex; var yPrefix; if(p.getY().toBigInteger().isEven()) yPrefix = "02"; else yPrefix = "03"; return yPrefix + xHex; } ECFieldElementFp.prototype.getR = function() { if(this.r != undefined) return this.r; this.r = null; var bitLength = this.q.bitLength(); if (bitLength > 128) { var firstWord = this.q.shiftRight(bitLength - 64); if (firstWord.intValue() == -1) { this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); } } return this.r; } ECFieldElementFp.prototype.modMult = function(x1,x2) { return this.modReduce(x1.multiply(x2)); } ECFieldElementFp.prototype.modReduce = function(x) { if (this.getR() != null) { var qLen = q.bitLength(); while (x.bitLength() > (qLen + 1)) { var u = x.shiftRight(qLen); var v = x.subtract(u.shiftLeft(qLen)); if (!this.getR().equals(BigInteger.ONE)) { u = u.multiply(this.getR()); } x = u.add(v); } while (x.compareTo(q) >= 0) { x = x.subtract(q); } } else { x = x.mod(q); } return x; } ECFieldElementFp.prototype.sqrt = function() { if (!this.q.testBit(0)) throw "unsupported"; // p mod 4 == 3 if (this.q.testBit(1)) { var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 var qMinusOne = this.q.subtract(BigInteger.ONE); var legendreExponent = qMinusOne.shiftRight(1); if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) { return null; } var u = qMinusOne.shiftRight(2); var k = u.shiftLeft(1).add(BigInteger.ONE); var Q = this.x; var fourQ = modDouble(modDouble(Q)); var U, V; do { var P; do { P = new BigInteger(this.q.bitLength(), new SecureRandom()); } while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); var result = this.lucasSequence(P, Q, k); U = result[0]; V = result[1]; if (this.modMult(V, V).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); return new ECFieldElementFp(q,V); } } while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); return null; } ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) { var n = k.bitLength(); var s = k.getLowestSetBit(); var Uh = BigInteger.ONE; var Vl = BigInteger.TWO; var Vh = P; var Ql = BigInteger.ONE; var Qh = BigInteger.ONE; for (var j = n - 1; j >= s + 1; --j) { Ql = this.modMult(Ql, Qh); if (k.testBit(j)) { Qh = this.modMult(Ql, Q); Uh = this.modMult(Uh, Vh); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); } else { Qh = Ql; Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); } } Ql = this.modMult(Ql, Qh); Qh = this.modMult(Ql, Q); Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Ql = this.modMult(Ql, Qh); for (var j = 1; j <= s; ++j) { Uh = this.modMult(Uh, Vl); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); Ql = this.modMult(Ql, Ql); } return [ Uh, Vl ]; } var exports = { ECCurveFp: ECCurveFp, ECPointFp: ECPointFp, ECFieldElementFp: ECFieldElementFp } module.exports = exports ```
/content/code_sandbox/node_modules/ecc-jsbn/lib/ec.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
4,448
```javascript // Named EC curves // Requires ec.js, jsbn.js, and jsbn2.js var BigInteger = require('jsbn').BigInteger var ECCurveFp = require('./ec.js').ECCurveFp // ---------------- // X9ECParameters // constructor function X9ECParameters(curve,g,n,h) { this.curve = curve; this.g = g; this.n = n; this.h = h; } function x9getCurve() { return this.curve; } function x9getG() { return this.g; } function x9getN() { return this.n; } function x9getH() { return this.h; } X9ECParameters.prototype.getCurve = x9getCurve; X9ECParameters.prototype.getG = x9getG; X9ECParameters.prototype.getN = x9getN; X9ECParameters.prototype.getH = x9getH; // ---------------- // SECNamedCurves function fromHex(s) { return new BigInteger(s, 16); } function secp128r1() { // p = 2^128 - 2^97 - 1 var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "161FF7528B899B2D0C28607CA52C5B86" + "CF5AC8395BAFEB13C02DA292DDED7A83"); return new X9ECParameters(curve, G, n, h); } function secp160k1() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); var a = BigInteger.ZERO; var b = fromHex("7"); //byte[] S = null; var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + "938CF935318FDCED6BC28286531733C3F03C4FEE"); return new X9ECParameters(curve, G, n, h); } function secp160r1() { // p = 2^160 - 2^31 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "4A96B5688EF573284664698968C38BB913CBFC82" + "23A628553168947D59DCC912042351377AC5FB32"); return new X9ECParameters(curve, G, n, h); } function secp192k1() { // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); var a = BigInteger.ZERO; var b = fromHex("3"); //byte[] S = null; var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); return new X9ECParameters(curve, G, n, h); } function secp192r1() { // p = 2^192 - 2^64 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); return new X9ECParameters(curve, G, n, h); } function secp224r1() { // p = 2^224 - 2^96 + 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); return new X9ECParameters(curve, G, n, h); } function secp256r1() { // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 var p = fromHex(your_sha256_hash); var a = fromHex(your_sha256_hash); var b = fromHex(your_sha256_hash); //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); var n = fromHex(your_sha256_hash); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + your_sha256_hash + your_sha256_hash); return new X9ECParameters(curve, G, n, h); } // TODO: make this into a proper hashtable function getSECCurveByName(name) { if(name == "secp128r1") return secp128r1(); if(name == "secp160k1") return secp160k1(); if(name == "secp160r1") return secp160r1(); if(name == "secp192k1") return secp192k1(); if(name == "secp192r1") return secp192r1(); if(name == "secp224r1") return secp224r1(); if(name == "secp256r1") return secp256r1(); return null; } module.exports = { "secp128r1":secp128r1, "secp160k1":secp160k1, "secp160r1":secp160r1, "secp192k1":secp192k1, "secp192r1":secp192r1, "secp224r1":secp224r1, "secp256r1":secp256r1 } ```
/content/code_sandbox/node_modules/ecc-jsbn/lib/sec.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,151
```javascript /** * For Node.js, simply re-export the core `util.deprecate` function. */ module.exports = require('util').deprecate; ```
/content/code_sandbox/node_modules/util-deprecate/node.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
33
```javascript /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } ```
/content/code_sandbox/node_modules/util-deprecate/browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
403
```javascript /* * verror.js: richer JavaScript errors */ var mod_assertplus = require('assert-plus'); var mod_util = require('util'); var mod_extsprintf = require('extsprintf'); var mod_isError = require('core-util-is').isError; var sprintf = mod_extsprintf.sprintf; /* * Public interface */ /* So you can 'var VError = require('verror')' */ module.exports = VError; /* For compatibility */ VError.VError = VError; /* Other exported classes */ VError.SError = SError; VError.WError = WError; VError.MultiError = MultiError; /* * Common function used to parse constructor arguments for VError, WError, and * SError. Named arguments to this function: * * strict force strict interpretation of sprintf arguments, even * if the options in "argv" don't say so * * argv error's constructor arguments, which are to be * interpreted as described in README.md. For quick * reference, "argv" has one of the following forms: * * [ sprintf_args... ] (argv[0] is a string) * [ cause, sprintf_args... ] (argv[0] is an Error) * [ options, sprintf_args... ] (argv[0] is an object) * * This function normalizes these forms, producing an object with the following * properties: * * options equivalent to "options" in third form. This will never * be a direct reference to what the caller passed in * (i.e., it may be a shallow copy), so it can be freely * modified. * * shortmessage result of sprintf(sprintf_args), taking options.strict * into account as described in README.md. */ function parseConstructorArguments(args) { var argv, options, sprintf_args, shortmessage, k; mod_assertplus.object(args, 'args'); mod_assertplus.bool(args.strict, 'args.strict'); mod_assertplus.array(args.argv, 'args.argv'); argv = args.argv; /* * First, figure out which form of invocation we've been given. */ if (argv.length === 0) { options = {}; sprintf_args = []; } else if (mod_isError(argv[0])) { options = { 'cause': argv[0] }; sprintf_args = argv.slice(1); } else if (typeof (argv[0]) === 'object') { options = {}; for (k in argv[0]) { options[k] = argv[0][k]; } sprintf_args = argv.slice(1); } else { mod_assertplus.string(argv[0], 'first argument to VError, SError, or WError ' + 'constructor must be a string, object, or Error'); options = {}; sprintf_args = argv; } /* * Now construct the error's message. * * extsprintf (which we invoke here with our caller's arguments in order * to construct this Error's message) is strict in its interpretation of * values to be processed by the "%s" specifier. The value passed to * extsprintf must actually be a string or something convertible to a * String using .toString(). Passing other values (notably "null" and * "undefined") is considered a programmer error. The assumption is * that if you actually want to print the string "null" or "undefined", * then that's easy to do that when you're calling extsprintf; on the * other hand, if you did NOT want that (i.e., there's actually a bug * where the program assumes some variable is non-null and tries to * print it, which might happen when constructing a packet or file in * some specific format), then it's better to stop immediately than * produce bogus output. * * However, sometimes the bug is only in the code calling VError, and a * programmer might prefer to have the error message contain "null" or * "undefined" rather than have the bug in the error path crash the * program (making the first bug harder to identify). For that reason, * by default VError converts "null" or "undefined" arguments to their * string representations and passes those to extsprintf. Programmers * desiring the strict behavior can use the SError class or pass the * "strict" option to the VError constructor. */ mod_assertplus.object(options); if (!options.strict && !args.strict) { sprintf_args = sprintf_args.map(function (a) { return (a === null ? 'null' : a === undefined ? 'undefined' : a); }); } if (sprintf_args.length === 0) { shortmessage = ''; } else { shortmessage = sprintf.apply(null, sprintf_args); } return ({ 'options': options, 'shortmessage': shortmessage }); } /* * See README.md for reference documentation. */ function VError() { var args, obj, parsed, cause, ctor, message, k; args = Array.prototype.slice.call(arguments, 0); /* * This is a regrettable pattern, but JavaScript's built-in Error class * is defined to work this way, so we allow the constructor to be called * without "new". */ if (!(this instanceof VError)) { obj = Object.create(VError.prototype); VError.apply(obj, arguments); return (obj); } /* * For convenience and backwards compatibility, we support several * different calling forms. Normalize them here. */ parsed = parseConstructorArguments({ 'argv': args, 'strict': false }); /* * If we've been given a name, apply it now. */ if (parsed.options.name) { mod_assertplus.string(parsed.options.name, 'error\'s "name" must be a string'); this.name = parsed.options.name; } /* * For debugging, we keep track of the original short message (attached * this Error particularly) separately from the complete message (which * includes the messages of our cause chain). */ this.jse_shortmsg = parsed.shortmessage; message = parsed.shortmessage; /* * If we've been given a cause, record a reference to it and update our * message appropriately. */ cause = parsed.options.cause; if (cause) { mod_assertplus.ok(mod_isError(cause), 'cause is not an Error'); this.jse_cause = cause; if (!parsed.options.skipCauseMessage) { message += ': ' + cause.message; } } /* * If we've been given an object with properties, shallow-copy that * here. We don't want to use a deep copy in case there are non-plain * objects here, but we don't want to use the original object in case * the caller modifies it later. */ this.jse_info = {}; if (parsed.options.info) { for (k in parsed.options.info) { this.jse_info[k] = parsed.options.info[k]; } } this.message = message; Error.call(this, message); if (Error.captureStackTrace) { ctor = parsed.options.constructorOpt || this.constructor; Error.captureStackTrace(this, ctor); } return (this); } mod_util.inherits(VError, Error); VError.prototype.name = 'VError'; VError.prototype.toString = function ve_toString() { var str = (this.hasOwnProperty('name') && this.name || this.constructor.name || this.constructor.prototype.name); if (this.message) str += ': ' + this.message; return (str); }; /* * This method is provided for compatibility. New callers should use * VError.cause() instead. That method also uses the saner `null` return value * when there is no cause. */ VError.prototype.cause = function ve_cause() { var cause = VError.cause(this); return (cause === null ? undefined : cause); }; /* * Static methods * * These class-level methods are provided so that callers can use them on * instances of Errors that are not VErrors. New interfaces should be provided * only using static methods to eliminate the class of programming mistake where * people fail to check whether the Error object has the corresponding methods. */ VError.cause = function (err) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); return (mod_isError(err.jse_cause) ? err.jse_cause : null); }; VError.info = function (err) { var rv, cause, k; mod_assertplus.ok(mod_isError(err), 'err must be an Error'); cause = VError.cause(err); if (cause !== null) { rv = VError.info(cause); } else { rv = {}; } if (typeof (err.jse_info) == 'object' && err.jse_info !== null) { for (k in err.jse_info) { rv[k] = err.jse_info[k]; } } return (rv); }; VError.findCauseByName = function (err, name) { var cause; mod_assertplus.ok(mod_isError(err), 'err must be an Error'); mod_assertplus.string(name, 'name'); mod_assertplus.ok(name.length > 0, 'name cannot be empty'); for (cause = err; cause !== null; cause = VError.cause(cause)) { mod_assertplus.ok(mod_isError(cause)); if (cause.name == name) { return (cause); } } return (null); }; VError.hasCauseWithName = function (err, name) { return (VError.findCauseByName(err, name) !== null); }; VError.fullStack = function (err) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); var cause = VError.cause(err); if (cause) { return (err.stack + '\ncaused by: ' + VError.fullStack(cause)); } return (err.stack); }; VError.errorFromList = function (errors) { mod_assertplus.arrayOfObject(errors, 'errors'); if (errors.length === 0) { return (null); } errors.forEach(function (e) { mod_assertplus.ok(mod_isError(e)); }); if (errors.length == 1) { return (errors[0]); } return (new MultiError(errors)); }; VError.errorForEach = function (err, func) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); mod_assertplus.func(func, 'func'); if (err instanceof MultiError) { err.errors().forEach(function iterError(e) { func(e); }); } else { func(err); } }; /* * SError is like VError, but stricter about types. You cannot pass "null" or * "undefined" as string arguments to the formatter. */ function SError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof SError)) { obj = Object.create(SError.prototype); SError.apply(obj, arguments); return (obj); } parsed = parseConstructorArguments({ 'argv': args, 'strict': true }); options = parsed.options; VError.call(this, options, '%s', parsed.shortmessage); return (this); } /* * We don't bother setting SError.prototype.name because once constructed, * SErrors are just like VErrors. */ mod_util.inherits(SError, VError); /* * Represents a collection of errors for the purpose of consumers that generally * only deal with one error. Callers can extract the individual errors * contained in this object, but may also just treat it as a normal single * error, in which case a summary message will be printed. */ function MultiError(errors) { mod_assertplus.array(errors, 'list of errors'); mod_assertplus.ok(errors.length > 0, 'must be at least one error'); this.ase_errors = errors; VError.call(this, { 'cause': errors[0] }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's'); } mod_util.inherits(MultiError, VError); MultiError.prototype.name = 'MultiError'; MultiError.prototype.errors = function me_errors() { return (this.ase_errors.slice(0)); }; /* * See README.md for reference details. */ function WError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof WError)) { obj = Object.create(WError.prototype); WError.apply(obj, args); return (obj); } parsed = parseConstructorArguments({ 'argv': args, 'strict': false }); options = parsed.options; options['skipCauseMessage'] = true; VError.call(this, options, '%s', parsed.shortmessage); return (this); } mod_util.inherits(WError, VError); WError.prototype.name = 'WError'; WError.prototype.toString = function we_toString() { var str = (this.hasOwnProperty('name') && this.name || this.constructor.name || this.constructor.prototype.name); if (this.message) str += ': ' + this.message; if (this.jse_cause && this.jse_cause.message) str += '; caused by ' + this.jse_cause.toString(); return (str); }; /* * For purely historical reasons, WError's cause() function allows you to set * the cause. */ WError.prototype.cause = function we_cause(c) { if (mod_isError(c)) this.jse_cause = c; return (this.jse_cause); }; ```
/content/code_sandbox/node_modules/verror/lib/verror.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,014
```javascript 'use strict' const MiniPass = require('minipass') const EE = require('events').EventEmitter const fs = require('fs') // for writev const binding = process.binding('fs') const writeBuffers = binding.writeBuffers /* istanbul ignore next */ const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') class ReadStream extends MiniPass { constructor (path, opt) { opt = opt || {} super(opt) this.writable = false if (typeof path !== 'string') throw new TypeError('path must be a string') this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16*1024*1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') this[_read]() else this[_open]() } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) return process.nextTick(() => this[_onread](null, 0, buf)) fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => this[_onread](er, br, buf)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) this[_onerror](er) else if (this[_handleChunk](br, buf)) this[_read]() } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { fs.close(this[_fd], _ => this.emit('close')) this[_fd] = null } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) ret = super.write(br < buf.length ? buf.slice(0, br) : buf) if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') this[_read]() break default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) this[_close]() } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) break } while (true) this[_reading] = false } threw = false } finally { if (threw) this[_close]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { try { fs.closeSync(this[_fd]) } catch (er) {} this[_fd] = null this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) this[_open]() } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_flush]() } } end (buf, enc) { if (buf) this.write(buf, enc) this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') this[_onwrite](null, 0) } write (buf, enc) { if (typeof buf === 'string') buf = new Buffer(buf, enc) if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) this[_onerror](er) else { if (this[_pos] !== null) this[_pos] += bw if (this[_queue].length) this[_flush]() else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) this[_onwrite](null, 0) } else if (this[_queue].length === 1) this[_write](this[_queue].pop()) else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { fs.close(this[_fd], _ => this.emit('close')) this[_fd] = null } } } class WriteStreamSync extends WriteStream { [_open] () { let fd try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else throw er } this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { try { fs.closeSync(this[_fd]) } catch (er) {} this[_fd] = null this.emit('close') } } [_write] (buf) { try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) } catch (er) { this[_onwrite](er, 0) } } } const writev = (fd, iovec, pos, cb) => { const done = (er, bw) => cb(er, bw, iovec) const req = new FSReqWrap() req.oncomplete = done binding.writeBuffers(fd, iovec, pos, req) } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync ```
/content/code_sandbox/node_modules/fs-minipass/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,654
```javascript 'use strict'; var parseUrl = require('url').parse; var DEFAULT_PORTS = { ftp: 21, gopher: 70, http: 80, https: 443, ws: 80, wss: 443, }; var stringEndsWith = String.prototype.endsWith || function(s) { return s.length <= this.length && this.indexOf(s, this.length - s.length) !== -1; }; /** * @param {string|object} url - The URL, or the result from url.parse. * @return {string} The URL of the proxy that should handle the request to the * given URL. If no proxy is set, this will be an empty string. */ function getProxyForUrl(url) { var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; var proto = parsedUrl.protocol; var hostname = parsedUrl.host; var port = parsedUrl.port; if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { return ''; // Don't proxy URLs without a valid scheme or host. } proto = proto.split(':', 1)[0]; // Stripping ports in this way instead of using parsedUrl.hostname to make // sure that the brackets around IPv6 addresses are kept. hostname = hostname.replace(/:\d*$/, ''); port = parseInt(port) || DEFAULT_PORTS[proto] || 0; if (!shouldProxy(hostname, port)) { return ''; // Don't proxy URLs that match NO_PROXY. } var proxy = getEnv('npm_config_' + proto + '_proxy') || getEnv(proto + '_proxy') || getEnv('npm_config_proxy') || getEnv('all_proxy'); if (proxy && proxy.indexOf('://') === -1) { // Missing scheme in proxy, default to the requested URL's scheme. proxy = proto + '://' + proxy; } return proxy; } /** * Determines whether a given URL should be proxied. * * @param {string} hostname - The host name of the URL. * @param {number} port - The effective port of the URL. * @returns {boolean} Whether the given URL should be proxied. * @private */ function shouldProxy(hostname, port) { var NO_PROXY = (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); if (!NO_PROXY) { return true; // Always proxy if NO_PROXY is not set. } if (NO_PROXY === '*') { return false; // Never proxy if wildcard is set. } return NO_PROXY.split(/[,\s]/).every(function(proxy) { if (!proxy) { return true; // Skip zero-length hosts. } var parsedProxy = proxy.match(/^(.+):(\d+)$/); var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; if (parsedProxyPort && parsedProxyPort !== port) { return true; // Skip if ports don't match. } if (!/^[.*]/.test(parsedProxyHostname)) { // No wildcards, so stop proxying if there is an exact match. return hostname !== parsedProxyHostname; } if (parsedProxyHostname.charAt(0) === '*') { // Remove leading wildcard. parsedProxyHostname = parsedProxyHostname.slice(1); } // Stop proxying if the hostname ends with the no_proxy host. return !stringEndsWith.call(hostname, parsedProxyHostname); }); } /** * Get the value for an environment variable. * * @param {string} key - The name of the environment variable. * @return {string} The value of the environment variable. * @private */ function getEnv(key) { return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; } exports.getProxyForUrl = getProxyForUrl; ```
/content/code_sandbox/node_modules/proxy-from-env/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
869
```javascript /* eslint max-statements:0 */ 'use strict'; var assert = require('assert'); var parseUrl = require('url').parse; var getProxyForUrl = require('./').getProxyForUrl; // Runs the callback with process.env temporarily set to env. function runWithEnv(env, callback) { var originalEnv = process.env; process.env = env; try { callback(); } finally { process.env = originalEnv; } } // Defines a test case that checks whether getProxyForUrl(input) === expected. function testProxyUrl(env, expected, input) { assert(typeof env === 'object' && env !== null); // Copy object to make sure that the in param does not get modified between // the call of this function and the use of it below. env = JSON.parse(JSON.stringify(env)); var title = 'getProxyForUrl(' + JSON.stringify(input) + ')' + ' === ' + JSON.stringify(expected); // Save call stack for later use. var stack = {}; Error.captureStackTrace(stack, testProxyUrl); // Only use the last stack frame because that shows where this function is // called, and that is sufficient for our purpose. No need to flood the logs // with an uninteresting stack trace. stack = stack.stack.split('\n', 2)[1]; it(title, function() { var actual; runWithEnv(env, function() { actual = getProxyForUrl(input); }); if (expected === actual) { return; // Good! } try { assert.strictEqual(expected, actual); // Create a formatted error message. // Should not happen because previously we determined expected !== actual. throw new Error('assert.strictEqual passed. This is impossible!'); } catch (e) { // Use the original stack trace, so we can see a helpful line number. e.stack = e.message + stack; throw e; } }); } describe('getProxyForUrl', function() { describe('No proxy variables', function() { var env = {}; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'ftp://example.com'); }); describe('Invalid URLs', function() { var env = {}; env.ALL_PROXY = 'path_to_url testProxyUrl(env, '', 'bogus'); testProxyUrl(env, '', '//example.com'); testProxyUrl(env, '', '://example.com'); testProxyUrl(env, '', '://'); testProxyUrl(env, '', '/path'); testProxyUrl(env, '', ''); testProxyUrl(env, '', 'http:'); testProxyUrl(env, '', 'http:/'); testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'prototype://'); testProxyUrl(env, '', 'hasOwnProperty://'); testProxyUrl(env, '', '__proto__://'); testProxyUrl(env, '', undefined); testProxyUrl(env, '', null); testProxyUrl(env, '', {}); testProxyUrl(env, '', {host: 'x', protocol: 1}); testProxyUrl(env, '', {host: 1, protocol: 'x'}); }); describe('http_proxy and HTTP_PROXY', function() { var env = {}; env.HTTP_PROXY = 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url parseUrl('path_to_url // eslint-disable-next-line camelcase env.http_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('http_proxy with non-sensical value', function() { var env = {}; // Crazy values should be passed as-is. It is the responsibility of the // one who launches the application that the value makes sense. // TODO: Should we be stricter and perform validation? env.HTTP_PROXY = 'Crazy \n!() { ::// }'; testProxyUrl(env, 'Crazy \n!() { ::// }', 'path_to_url // The implementation assumes that the HTTP_PROXY environment variable is // somewhat reasonable, and if the scheme is missing, it is added. // Garbage in, garbage out some would say... env.HTTP_PROXY = 'crazy without colon slash slash'; testProxyUrl(env, 'path_to_url without colon slash slash', 'path_to_url }); describe('https_proxy and HTTPS_PROXY', function() { var env = {}; // Assert that there is no fall back to http_proxy env.HTTP_PROXY = 'path_to_url testProxyUrl(env, '', 'path_to_url env.HTTPS_PROXY = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url // eslint-disable-next-line camelcase env.https_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('ftp_proxy', function() { var env = {}; // Something else than http_proxy / https, as a sanity check. env.FTP_PROXY = 'path_to_url testProxyUrl(env, 'path_to_url 'ftp://example'); testProxyUrl(env, '', 'ftps://example'); }); describe('all_proxy', function() { var env = {}; env.ALL_PROXY = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url // eslint-disable-next-line camelcase env.all_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('all_proxy without scheme', function() { var env = {}; env.ALL_PROXY = 'noscheme'; testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url // The module does not impose restrictions on the scheme. testProxyUrl(env, 'bogus-scheme://noscheme', 'bogus-scheme://example'); // But the URL should still be valid. testProxyUrl(env, '', 'bogus'); }); describe('no_proxy empty', function() { var env = {}; env.HTTPS_PROXY = 'path_to_url // NO_PROXY set but empty. env.NO_PROXY = ''; testProxyUrl(env, 'path_to_url 'path_to_url // No entries in NO_PROXY (comma). env.NO_PROXY = ','; testProxyUrl(env, 'path_to_url 'path_to_url // No entries in NO_PROXY (whitespace). env.NO_PROXY = ' '; testProxyUrl(env, 'path_to_url 'path_to_url // No entries in NO_PROXY (multiple whitespace / commas). env.NO_PROXY = ',\t,,,\n, ,\r'; testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=example (single host)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = 'example'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=sub.example (subdomain)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = 'sub.example'; testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=example:80 (host + port)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = 'example:80'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=.example (host suffix)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '.example'; testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'path_to_url }); describe('no_proxy=*', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '*'; testProxyUrl(env, '', 'path_to_url }); describe('no_proxy=*.example (host suffix with *.)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '*.example'; testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'path_to_url }); describe('no_proxy=*example (substring suffix)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '*example'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=.*example (arbitrary wildcards are NOT supported)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '.*example'; testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=[::1],[::2]:80,10.0.0.1,10.0.0.2:80 (IP addresses)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '[::1],[::2]:80,10.0.0.1,10.0.0.2:80'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=127.0.0.1/32 (CIDR is NOT supported)', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '127.0.0.1/32'; testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy=127.0.0.1 does NOT match localhost', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = '127.0.0.1'; testProxyUrl(env, '', 'path_to_url // We're not performing DNS queries, so this shouldn't match. testProxyUrl(env, 'path_to_url 'path_to_url }); describe('no_proxy with protocols that have a default port', function() { var env = {}; env.WS_PROXY = 'path_to_url env.WSS_PROXY = 'path_to_url env.HTTP_PROXY = 'path_to_url env.HTTPS_PROXY = 'path_to_url env.GOPHER_PROXY = 'path_to_url env.FTP_PROXY = 'path_to_url env.ALL_PROXY = 'path_to_url env.NO_PROXY = 'xxx:21,xxx:70,xxx:80,xxx:443'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'ws://xxx'); testProxyUrl(env, '', 'ws://xxx:80'); testProxyUrl(env, 'path_to_url 'ws://xxx:1337'); testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, '', 'wss://xxx'); testProxyUrl(env, '', 'wss://xxx:443'); testProxyUrl(env, 'path_to_url 'wss://xxx:1337'); testProxyUrl(env, '', 'gopher://xxx'); testProxyUrl(env, '', 'gopher://xxx:70'); testProxyUrl(env, 'path_to_url 'gopher://xxx:1337'); testProxyUrl(env, '', 'ftp://xxx'); testProxyUrl(env, '', 'ftp://xxx:21'); testProxyUrl(env, 'path_to_url 'ftp://xxx:1337'); }); describe('no_proxy should not be case-sensitive', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = 'XXX,YYY,ZzZ'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, '', 'path_to_url }); describe('NPM proxy configuration', function() { describe('npm_config_http_proxy should work', function() { var env = {}; // eslint-disable-next-line camelcase env.npm_config_http_proxy = 'path_to_url testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url // eslint-disable-next-line camelcase env.npm_config_http_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); // eslint-disable-next-line max-len describe('npm_config_http_proxy should take precedence over HTTP_PROXY and npm_config_proxy', function() { var env = {}; // eslint-disable-next-line camelcase env.npm_config_http_proxy = 'path_to_url // eslint-disable-next-line camelcase env.npm_config_proxy = 'path_to_url env.HTTP_PROXY = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('npm_config_https_proxy should work', function() { var env = {}; // eslint-disable-next-line camelcase env.npm_config_http_proxy = 'path_to_url testProxyUrl(env, '', 'path_to_url // eslint-disable-next-line camelcase env.npm_config_https_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url // eslint-disable-next-line camelcase env.npm_config_https_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); // eslint-disable-next-line max-len describe('npm_config_https_proxy should take precedence over HTTPS_PROXY and npm_config_proxy', function() { var env = {}; // eslint-disable-next-line camelcase env.npm_config_https_proxy = 'path_to_url // eslint-disable-next-line camelcase env.npm_config_proxy = 'path_to_url env.HTTPS_PROXY = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('npm_config_proxy should work', function() { var env = {}; // eslint-disable-next-line camelcase env.npm_config_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url // eslint-disable-next-line camelcase env.npm_config_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); // eslint-disable-next-line max-len describe('HTTP_PROXY and HTTPS_PROXY should take precedence over npm_config_proxy', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.HTTPS_PROXY = 'path_to_url // eslint-disable-next-line camelcase env.npm_config_proxy = 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); describe('npm_config_no_proxy should work', function() { var env = {}; env.HTTP_PROXY = 'path_to_url // eslint-disable-next-line camelcase env.npm_config_no_proxy = 'example'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); // eslint-disable-next-line max-len describe('npm_config_no_proxy should take precedence over NO_PROXY', function() { var env = {}; env.HTTP_PROXY = 'path_to_url env.NO_PROXY = 'otherwebsite'; // eslint-disable-next-line camelcase env.npm_config_no_proxy = 'example'; testProxyUrl(env, '', 'path_to_url testProxyUrl(env, 'path_to_url 'path_to_url }); }); }); ```
/content/code_sandbox/node_modules/proxy-from-env/test.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
4,462
```javascript var aws4 = exports, url = require('url'), querystring = require('querystring'), crypto = require('crypto'), lru = require('./lru'), credentialsCache = lru(1000) // path_to_url function hmac(key, string, encoding) { return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) } function hash(string, encoding) { return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) } // This function assumes the string has already been percent encoded function encodeRfc3986(urlEncodedString) { return urlEncodedString.replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } function encodeRfc3986Full(str) { return encodeRfc3986(encodeURIComponent(str)) } // A bit of a combination of: // path_to_url#L59 // path_to_url#L191-L199 // path_to_url#L25-L34 var HEADERS_TO_IGNORE = { 'authorization': true, 'connection': true, 'x-amzn-trace-id': true, 'user-agent': true, 'expect': true, 'presigned-expires': true, 'range': true, } // request: { path | body, [host], [method], [headers], [service], [region] } // credentials: { accessKeyId, secretAccessKey, [sessionToken] } function RequestSigner(request, credentials) { if (typeof request === 'string') request = url.parse(request) var headers = request.headers = (request.headers || {}), hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) this.request = request this.credentials = credentials || this.defaultCredentials() this.service = request.service || hostParts[0] || '' this.region = request.region || hostParts[1] || 'us-east-1' // SES uses a different domain from the service name if (this.service === 'email') this.service = 'ses' if (!request.method && request.body) request.method = 'POST' if (!headers.Host && !headers.host) { headers.Host = request.hostname || request.host || this.createHost() // If a port is specified explicitly, use it as is if (request.port) headers.Host += ':' + request.port } if (!request.hostname && !request.host) request.hostname = headers.Host || headers.host this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' } RequestSigner.prototype.matchHost = function(host) { var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) var hostParts = (match || []).slice(1, 3) // ES's hostParts are sometimes the other way round, if the value that is expected // to be region equals es switch them back // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com if (hostParts[1] === 'es') hostParts = hostParts.reverse() if (hostParts[1] == 's3') { hostParts[0] = 's3' hostParts[1] = 'us-east-1' } else { for (var i = 0; i < 2; i++) { if (/^s3-/.test(hostParts[i])) { hostParts[1] = hostParts[i].slice(3) hostParts[0] = 's3' break } } } return hostParts } // path_to_url RequestSigner.prototype.isSingleRegion = function() { // Special case for S3 and SimpleDB in us-east-1 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] .indexOf(this.service) >= 0 } RequestSigner.prototype.createHost = function() { var region = this.isSingleRegion() ? '' : '.' + this.region, subdomain = this.service === 'ses' ? 'email' : this.service return subdomain + region + '.amazonaws.com' } RequestSigner.prototype.prepareRequest = function() { this.parsePath() var request = this.request, headers = request.headers, query if (request.signQuery) { this.parsedPath.query = query = this.parsedPath.query || {} if (this.credentials.sessionToken) query['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !query['X-Amz-Expires']) query['X-Amz-Expires'] = 86400 if (query['X-Amz-Date']) this.datetime = query['X-Amz-Date'] else query['X-Amz-Date'] = this.getDateTime() query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() query['X-Amz-SignedHeaders'] = this.signedHeaders() } else { if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { if (request.body && !headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' if (request.body && !headers['Content-Length'] && !headers['content-length']) headers['Content-Length'] = Buffer.byteLength(request.body) if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) headers['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') if (headers['X-Amz-Date'] || headers['x-amz-date']) this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] else headers['X-Amz-Date'] = this.getDateTime() } delete headers.Authorization delete headers.authorization } } RequestSigner.prototype.sign = function() { if (!this.parsedPath) this.prepareRequest() if (this.request.signQuery) { this.parsedPath.query['X-Amz-Signature'] = this.signature() } else { this.request.headers.Authorization = this.authHeader() } this.request.path = this.formatPath() return this.request } RequestSigner.prototype.getDateTime = function() { if (!this.datetime) { var headers = this.request.headers, date = new Date(headers.Date || headers.date || new Date) this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') // Remove the trailing 'Z' on the timestamp string for CodeCommit git access if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) } return this.datetime } RequestSigner.prototype.getDate = function() { return this.getDateTime().substr(0, 8) } RequestSigner.prototype.authHeader = function() { return [ 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), 'SignedHeaders=' + this.signedHeaders(), 'Signature=' + this.signature(), ].join(', ') } RequestSigner.prototype.signature = function() { var date = this.getDate(), cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) if (!kCredentials) { kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) kRegion = hmac(kDate, this.region) kService = hmac(kRegion, this.service) kCredentials = hmac(kService, 'aws4_request') credentialsCache.set(cacheKey, kCredentials) } return hmac(kCredentials, this.stringToSign(), 'hex') } RequestSigner.prototype.stringToSign = function() { return [ 'AWS4-HMAC-SHA256', this.getDateTime(), this.credentialString(), hash(this.canonicalString(), 'hex'), ].join('\n') } RequestSigner.prototype.canonicalString = function() { if (!this.parsedPath) this.prepareRequest() var pathStr = this.parsedPath.path, query = this.parsedPath.query, headers = this.request.headers, queryStr = '', normalizePath = this.service !== 's3', decodePath = this.service === 's3' || this.request.doNotEncodePath, decodeSlashesInPath = this.service === 's3', firstValOnly = this.service === 's3', bodyHash if (this.service === 's3' && this.request.signQuery) { bodyHash = 'UNSIGNED-PAYLOAD' } else if (this.isCodeCommitGit) { bodyHash = '' } else { bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || hash(this.request.body || '', 'hex') } if (query) { var reducedQuery = Object.keys(query).reduce(function(obj, key) { if (!key) return obj obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : (firstValOnly ? query[key][0] : query[key]) return obj }, {}) var encodedQueryPieces = [] Object.keys(reducedQuery).sort().forEach(function(key) { if (!Array.isArray(reducedQuery[key])) { encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) } else { reducedQuery[key].map(encodeRfc3986Full).sort() .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) } }) queryStr = encodedQueryPieces.join('&') } if (pathStr !== '/') { if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') pathStr = pathStr.split('/').reduce(function(path, piece) { if (normalizePath && piece === '..') { path.pop() } else if (!normalizePath || piece !== '.') { if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' ')) path.push(encodeRfc3986Full(piece)) } return path }, []).join('/') if (pathStr[0] !== '/') pathStr = '/' + pathStr if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') } return [ this.request.method || 'GET', pathStr, queryStr, this.canonicalHeaders() + '\n', this.signedHeaders(), bodyHash, ].join('\n') } RequestSigner.prototype.canonicalHeaders = function() { var headers = this.request.headers function trimAll(header) { return header.toString().trim().replace(/\s+/g, ' ') } return Object.keys(headers) .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) .join('\n') } RequestSigner.prototype.signedHeaders = function() { return Object.keys(this.request.headers) .map(function(key) { return key.toLowerCase() }) .filter(function(key) { return HEADERS_TO_IGNORE[key] == null }) .sort() .join(';') } RequestSigner.prototype.credentialString = function() { return [ this.getDate(), this.region, this.service, 'aws4_request', ].join('/') } RequestSigner.prototype.defaultCredentials = function() { var env = process.env return { accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, sessionToken: env.AWS_SESSION_TOKEN, } } RequestSigner.prototype.parsePath = function() { var path = this.request.path || '/' // S3 doesn't always encode characters > 127 correctly and // all services don't encode characters > 255 correctly // So if there are non-reserved chars (and it's not already all % encoded), just encode them all if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { path = encodeURI(decodeURI(path)) } var queryIx = path.indexOf('?'), query = null if (queryIx >= 0) { query = querystring.parse(path.slice(queryIx + 1)) path = path.slice(0, queryIx) } this.parsedPath = { path: path, query: query, } } RequestSigner.prototype.formatPath = function() { var path = this.parsedPath.path, query = this.parsedPath.query if (!query) return path // Services don't support empty query string keys if (query[''] != null) delete query[''] return path + '?' + encodeRfc3986(querystring.stringify(query)) } aws4.RequestSigner = RequestSigner aws4.sign = function(request, credentials) { return new RequestSigner(request, credentials).sign() } ```
/content/code_sandbox/node_modules/aws4/aws4.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,084
```javascript module.exports = function(size) { return new LruCache(size) } function LruCache(size) { this.capacity = size | 0 this.map = Object.create(null) this.list = new DoublyLinkedList() } LruCache.prototype.get = function(key) { var node = this.map[key] if (node == null) return undefined this.used(node) return node.val } LruCache.prototype.set = function(key, val) { var node = this.map[key] if (node != null) { node.val = val } else { if (!this.capacity) this.prune() if (!this.capacity) return false node = new DoublyLinkedNode(key, val) this.map[key] = node this.capacity-- } this.used(node) return true } LruCache.prototype.used = function(node) { this.list.moveToFront(node) } LruCache.prototype.prune = function() { var node = this.list.pop() if (node != null) { delete this.map[node.key] this.capacity++ } } function DoublyLinkedList() { this.firstNode = null this.lastNode = null } DoublyLinkedList.prototype.moveToFront = function(node) { if (this.firstNode == node) return this.remove(node) if (this.firstNode == null) { this.firstNode = node this.lastNode = node node.prev = null node.next = null } else { node.prev = null node.next = this.firstNode node.next.prev = node this.firstNode = node } } DoublyLinkedList.prototype.pop = function() { var lastNode = this.lastNode if (lastNode != null) { this.remove(lastNode) } return lastNode } DoublyLinkedList.prototype.remove = function(node) { if (this.firstNode == node) { this.firstNode = node.next } else if (node.prev != null) { node.prev.next = node.next } if (this.lastNode == node) { this.lastNode = node.prev } else if (node.next != null) { node.next.prev = node.prev } } function DoublyLinkedNode(key, val) { this.key = key this.val = val this.prev = null this.next = null } ```
/content/code_sandbox/node_modules/aws4/lru.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
528
```javascript try { var util = require('util'); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = require('./inherits_browser.js'); } ```
/content/code_sandbox/node_modules/inherits/inherits.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
65
```javascript if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } ```
/content/code_sandbox/node_modules/inherits/inherits_browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
182
```javascript "use strict"; module.exports = parse; var re_name = /^(?:\\.|[\w\-\u00b0-\uFFFF])+/, re_escape = /\\([\da-f]{1,6}\s?|(\s)|.)/ig, //modified version of path_to_url#L87 re_attr = /^\s*((?:\\.|[\w\u00b0-\uFFFF\-])+)\s*(?:(\S?)=\s*(?:(['"])([^]*?)\3|(#?(?:\\.|[\w\u00b0-\uFFFF\-])*)|)|)\s*(i)?\]/; var actionTypes = { __proto__: null, "undefined": "exists", "": "equals", "~": "element", "^": "start", "$": "end", "*": "any", "!": "not", "|": "hyphen" }; var simpleSelectors = { __proto__: null, ">": "child", "<": "parent", "~": "sibling", "+": "adjacent" }; var attribSelectors = { __proto__: null, "#": ["id", "equals"], ".": ["class", "element"] }; //pseudos, whose data-property is parsed as well var unpackPseudos = { __proto__: null, "has": true, "not": true, "matches": true }; var stripQuotesFromPseudos = { __proto__: null, "contains": true, "icontains": true }; var quotes = { __proto__: null, "\"": true, "'": true }; //unescape function taken from path_to_url#L139 function funescape( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); } function unescapeCSS(str){ return str.replace(re_escape, funescape); } function isWhitespace(c){ return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r"; } function parse(selector, options){ var subselects = []; selector = parseSelector(subselects, selector + "", options); if(selector !== ""){ throw new SyntaxError("Unmatched selector: " + selector); } return subselects; } function parseSelector(subselects, selector, options){ var tokens = [], sawWS = false, data, firstChar, name, quot; function getName(){ var sub = selector.match(re_name)[0]; selector = selector.substr(sub.length); return unescapeCSS(sub); } function stripWhitespace(start){ while(isWhitespace(selector.charAt(start))) start++; selector = selector.substr(start); } function isEscaped(pos) { var slashCount = 0; while (selector.charAt(--pos) === "\\") slashCount++; return (slashCount & 1) === 1; } stripWhitespace(0); while(selector !== ""){ firstChar = selector.charAt(0); if(isWhitespace(firstChar)){ sawWS = true; stripWhitespace(1); } else if(firstChar in simpleSelectors){ tokens.push({type: simpleSelectors[firstChar]}); sawWS = false; stripWhitespace(1); } else if(firstChar === ","){ if(tokens.length === 0){ throw new SyntaxError("empty sub-selector"); } subselects.push(tokens); tokens = []; sawWS = false; stripWhitespace(1); } else { if(sawWS){ if(tokens.length > 0){ tokens.push({type: "descendant"}); } sawWS = false; } if(firstChar === "*"){ selector = selector.substr(1); tokens.push({type: "universal"}); } else if(firstChar in attribSelectors){ selector = selector.substr(1); tokens.push({ type: "attribute", name: attribSelectors[firstChar][0], action: attribSelectors[firstChar][1], value: getName(), ignoreCase: false }); } else if(firstChar === "["){ selector = selector.substr(1); data = selector.match(re_attr); if(!data){ throw new SyntaxError("Malformed attribute selector: " + selector); } selector = selector.substr(data[0].length); name = unescapeCSS(data[1]); if( !options || ( "lowerCaseAttributeNames" in options ? options.lowerCaseAttributeNames : !options.xmlMode ) ){ name = name.toLowerCase(); } tokens.push({ type: "attribute", name: name, action: actionTypes[data[2]], value: unescapeCSS(data[4] || data[5] || ""), ignoreCase: !!data[6] }); } else if(firstChar === ":"){ if(selector.charAt(1) === ":"){ selector = selector.substr(2); tokens.push({type: "pseudo-element", name: getName().toLowerCase()}); continue; } selector = selector.substr(1); name = getName().toLowerCase(); data = null; if(selector.charAt(0) === "("){ if(name in unpackPseudos){ quot = selector.charAt(1); var quoted = quot in quotes; selector = selector.substr(quoted + 1); data = []; selector = parseSelector(data, selector, options); if(quoted){ if(selector.charAt(0) !== quot){ throw new SyntaxError("unmatched quotes in :" + name); } else { selector = selector.substr(1); } } if(selector.charAt(0) !== ")"){ throw new SyntaxError("missing closing parenthesis in :" + name + " " + selector); } selector = selector.substr(1); } else { var pos = 1, counter = 1; for(; counter > 0 && pos < selector.length; pos++){ if(selector.charAt(pos) === "(" && !isEscaped(pos)) counter++; else if(selector.charAt(pos) === ")" && !isEscaped(pos)) counter--; } if(counter){ throw new SyntaxError("parenthesis not matched"); } data = selector.substr(1, pos - 2); selector = selector.substr(pos); if(name in stripQuotesFromPseudos){ quot = data.charAt(0); if(quot === data.slice(-1) && quot in quotes){ data = data.slice(1, -1); } data = unescapeCSS(data); } } } tokens.push({type: "pseudo", name: name, data: data}); } else if(re_name.test(selector)){ name = getName(); if(!options || ("lowerCaseTags" in options ? options.lowerCaseTags : !options.xmlMode)){ name = name.toLowerCase(); } tokens.push({type: "tag", name: name}); } else { if(tokens.length && tokens[tokens.length - 1].type === "descendant"){ tokens.pop(); } addToken(subselects, tokens); return selector; } } } addToken(subselects, tokens); return selector; } function addToken(subselects, tokens){ if(subselects.length > 0 && tokens.length === 0){ throw new SyntaxError("empty sub-selector"); } subselects.push(tokens); } ```
/content/code_sandbox/node_modules/css-what/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,779
```javascript var crypto = require('crypto') function sha (key, body, algorithm) { return crypto.createHmac(algorithm, key).update(body).digest('base64') } function rsa (key, body) { return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64') } function rfc3986 (str) { return encodeURIComponent(str) .replace(/!/g,'%21') .replace(/\*/g,'%2A') .replace(/\(/g,'%28') .replace(/\)/g,'%29') .replace(/'/g,'%27') } // Maps object to bi-dimensional array // Converts { foo: 'A', bar: [ 'b', 'B' ]} to // [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ] function map (obj) { var key, val, arr = [] for (key in obj) { val = obj[key] if (Array.isArray(val)) for (var i = 0; i < val.length; i++) arr.push([key, val[i]]) else if (typeof val === 'object') for (var prop in val) arr.push([key + '[' + prop + ']', val[prop]]) else arr.push([key, val]) } return arr } // Compare function for sort function compare (a, b) { return a > b ? 1 : a < b ? -1 : 0 } function generateBase (httpMethod, base_uri, params) { // adapted from path_to_url and // path_to_url // Parameter normalization // path_to_url#section-3.4.1.3.2 var normalized = map(params) // 1. First, the name and value of each parameter are encoded .map(function (p) { return [ rfc3986(p[0]), rfc3986(p[1] || '') ] }) // 2. The parameters are sorted by name, using ascending byte value // ordering. If two or more parameters share the same name, they // are sorted by their value. .sort(function (a, b) { return compare(a[0], b[0]) || compare(a[1], b[1]) }) // 3. The name of each parameter is concatenated to its corresponding // value using an "=" character (ASCII code 61) as a separator, even // if the value is empty. .map(function (p) { return p.join('=') }) // 4. The sorted name/value pairs are concatenated together into a // single string by using an "&" character (ASCII code 38) as // separator. .join('&') var base = [ rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'), rfc3986(base_uri), rfc3986(normalized) ].join('&') return base } function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return sha(key, base, 'sha1') } function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return sha(key, base, 'sha256') } function rsasign (httpMethod, base_uri, params, private_key, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = private_key || '' return rsa(key, base) } function plaintext (consumer_secret, token_secret) { var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return key } function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) { var method var skipArgs = 1 switch (signMethod) { case 'RSA-SHA1': method = rsasign break case 'HMAC-SHA1': method = hmacsign break case 'HMAC-SHA256': method = hmacsign256 break case 'PLAINTEXT': method = plaintext skipArgs = 4 break default: throw new Error('Signature method not supported: ' + signMethod) } return method.apply(null, [].slice.call(arguments, skipArgs)) } exports.hmacsign = hmacsign exports.hmacsign256 = hmacsign256 exports.rsasign = rsasign exports.plaintext = plaintext exports.sign = sign exports.rfc3986 = rfc3986 exports.generateBase = generateBase ```
/content/code_sandbox/node_modules/oauth-sign/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,105
```javascript var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; ```
/content/code_sandbox/node_modules/foreach/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
146
```javascript var test = require('tape'); var forEach = require('./index.js'); test('second argument: iterator', function (t) { var arr = []; t.throws(function () { forEach(arr); }, TypeError, 'undefined is not a function'); t.throws(function () { forEach(arr, null); }, TypeError, 'null is not a function'); t.throws(function () { forEach(arr, ''); }, TypeError, 'string is not a function'); t.throws(function () { forEach(arr, /a/); }, TypeError, 'regex is not a function'); t.throws(function () { forEach(arr, true); }, TypeError, 'true is not a function'); t.throws(function () { forEach(arr, false); }, TypeError, 'false is not a function'); t.throws(function () { forEach(arr, NaN); }, TypeError, 'NaN is not a function'); t.throws(function () { forEach(arr, 42); }, TypeError, '42 is not a function'); t.doesNotThrow(function () { forEach(arr, function () {}); }, 'function is a function'); t.end(); }); test('array', function (t) { var arr = [1, 2, 3]; t.test('iterates over every item', function (st) { var index = 0; forEach(arr, function () { index += 1; }); st.equal(index, arr.length, 'iterates ' + arr.length + ' times'); st.end(); }); t.test('first iterator argument', function (st) { var index = 0; st.plan(arr.length); forEach(arr, function (item) { st.equal(arr[index], item, 'item ' + index + ' is passed as first argument'); index += 1; }); st.end(); }); t.test('second iterator argument', function (st) { var counter = 0; st.plan(arr.length); forEach(arr, function (item, index) { st.equal(counter, index, 'index ' + index + ' is passed as second argument'); counter += 1; }); st.end(); }); t.test('third iterator argument', function (st) { st.plan(arr.length); forEach(arr, function (item, index, array) { st.deepEqual(arr, array, 'array is passed as third argument'); }); st.end(); }); t.test('context argument', function (st) { var context = {}; st.plan(1); forEach([1], function () { st.equal(this, context, '"this" is the passed context'); }, context); st.end(); }); t.end(); }); test('object', function (t) { var obj = { a: 1, b: 2, c: 3 }; var keys = ['a', 'b', 'c']; var F = function () { this.a = 1; this.b = 2; }; F.prototype.c = 3; var fKeys = ['a', 'b']; t.test('iterates over every object literal key', function (st) { var counter = 0; forEach(obj, function () { counter += 1; }); st.equal(counter, keys.length, 'iterated ' + counter + ' times'); st.end(); }); t.test('iterates only over own keys', function (st) { var counter = 0; forEach(new F(), function () { counter += 1; }); st.equal(counter, fKeys.length, 'iterated ' + fKeys.length + ' times'); st.end(); }); t.test('first iterator argument', function (st) { var index = 0; st.plan(keys.length); forEach(obj, function (item) { st.equal(obj[keys[index]], item, 'item at key ' + keys[index] + ' is passed as first argument'); index += 1; }); st.end(); }); t.test('second iterator argument', function (st) { var counter = 0; st.plan(keys.length); forEach(obj, function (item, key) { st.equal(keys[counter], key, 'key ' + key + ' is passed as second argument'); counter += 1; }); st.end(); }); t.test('third iterator argument', function (st) { st.plan(keys.length); forEach(obj, function (item, key, object) { st.deepEqual(obj, object, 'object is passed as third argument'); }); st.end(); }); t.test('context argument', function (st) { var context = {}; st.plan(1); forEach({ a: 1 }, function () { st.equal(this, context, '"this" is the passed context'); }, context); st.end(); }); t.end(); }); test('string', function (t) { var str = 'str'; t.test('second iterator argument', function (st) { var counter = 0; st.plan(str.length * 2 + 1); forEach(str, function (item, index) { st.equal(counter, index, 'index ' + index + ' is passed as second argument'); st.equal(str.charAt(index), item); counter += 1; }); st.equal(counter, str.length, 'iterates ' + str.length + ' times'); }); t.end(); }); ```
/content/code_sandbox/node_modules/foreach/test.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,176
```javascript "use strict"; /** * Returns a `Buffer` instance from the given data URI `uri`. * * @param {String} uri Data URI to turn into a Buffer instance * @return {Buffer} Buffer instance from Data URI * @api public */ function dataUriToBuffer(uri) { if (!/^data:/i.test(uri)) { throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); } // strip newlines uri = uri.replace(/\r?\n/g, ''); // split the URI up into the "metadata" and the "data" portions const firstComma = uri.indexOf(','); if (firstComma === -1 || firstComma <= 4) { throw new TypeError('malformed data: URI'); } // remove the "data:" scheme and parse the metadata const meta = uri.substring(5, firstComma).split(';'); let charset = ''; let base64 = false; const type = meta[0] || 'text/plain'; let typeFull = type; for (let i = 1; i < meta.length; i++) { if (meta[i] === 'base64') { base64 = true; } else { typeFull += `;${meta[i]}`; if (meta[i].indexOf('charset=') === 0) { charset = meta[i].substring(8); } } } // defaults to US-ASCII only if type is not provided if (!meta[0] && !charset.length) { typeFull += ';charset=US-ASCII'; charset = 'US-ASCII'; } // get the encoded data portion and decode URI-encoded chars const encoding = base64 ? 'base64' : 'ascii'; const data = unescape(uri.substring(firstComma + 1)); const buffer = Buffer.from(data, encoding); // set `.type` and `.typeFull` properties to MIME type buffer.type = type; buffer.typeFull = typeFull; // set the `.charset` property buffer.charset = charset; return buffer; } module.exports = dataUriToBuffer; //# sourceMappingURL=index.js.map ```
/content/code_sandbox/node_modules/data-uri-to-buffer/dist/src/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
484
```javascript "use strict"; var util = require('util'); var cssstyle = require('../lib/CSSStyleDeclaration'); var camelToDashed = require('../lib/parsers').camelToDashed; /** * These are the required properties * see path_to_url#CSS-CSS2Properties **/ var properties = [ 'azimuth', 'background', 'backgroundAttachment', 'backgroundColor', 'backgroundImage', 'backgroundPosition', 'backgroundRepeat', 'border', 'borderCollapse', 'borderColor', 'borderSpacing', 'borderStyle', 'borderTop', 'borderRight', 'borderBottom', 'borderLeft', 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor', 'borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderWidth', 'bottom', 'captionSide', 'clear', 'clip', 'color', 'content', 'counterIncrement', 'counterReset', 'cue', 'cueAfter', 'cueBefore', 'cursor', 'direction', 'display', 'elevation', 'emptyCells', 'cssFloat', 'font', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'height', 'left', 'letterSpacing', 'lineHeight', 'listStyle', 'listStyleImage', 'listStylePosition', 'listStyleType', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'markerOffset', 'marks', 'maxHeight', 'maxWidth', 'minHeight', 'minWidth', 'orphans', 'outline', 'outlineColor', 'outlineStyle', 'outlineWidth', 'overflow', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'page', 'pageBreakAfter', 'pageBreakBefore', 'pageBreakInside', 'pause', 'pauseAfter', 'pauseBefore', 'pitch', 'pitchRange', 'playDuring', 'position', 'quotes', 'richness', 'right', 'size', 'speak', 'speakHeader', 'speakNumeral', 'speakPunctuation', 'speechRate', 'stress', 'tableLayout', 'textAlign', 'textDecoration', 'textIndent', 'textShadow', 'textTransform', 'top', 'unicodeBidi', 'verticalAlign', 'visibility', 'voiceFamily', 'volume', 'whiteSpace', 'widows', 'width', 'wordSpacing', 'zIndex']; var dashed_properties = properties.map(function (property) { return camelToDashed(property); }); module.exports = { 'Verify Has Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(properties.length * 2); properties.forEach(function (property) { test.ok(style.__lookupGetter__(property), 'missing ' + property + ' property'); test.ok(style.__lookupSetter__(property), 'missing ' + property + ' property'); }); test.done(); }, 'Verify Has Dashed Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(dashed_properties.length * 2); dashed_properties.forEach(function (property) { test.ok(style.__lookupGetter__(property), 'missing ' + property + ' property'); test.ok(style.__lookupSetter__(property), 'missing ' + property + ' property'); }); test.done(); }, 'Verify Has Functions': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(6); test.ok(typeof style.getPropertyValue === 'function', 'missing getPropertyValue()'); test.ok(typeof style.getPropertyCSSValue === 'function', 'missing getPropertyCSSValue()'); test.ok(typeof style.removeProperty === 'function', 'missing removeProperty()'); test.ok(typeof style.getPropertyPriority === 'function', 'missing getPropertyPriority()'); test.ok(typeof style.setProperty === 'function', 'missing setProperty()'); test.ok(typeof style.item === 'function', 'missing item()'); test.done(); }, 'Verify Has Special Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(5); test.ok(style.__lookupGetter__('cssText'), 'missing cssText getter'); test.ok(style.__lookupSetter__('cssText'), 'missing cssText setter'); test.ok(style.__lookupGetter__('length'), 'missing length getter'); test.ok(style.__lookupSetter__('length'), 'missing length setter'); test.ok(style.__lookupGetter__('parentRule'), 'missing parentRule getter'); test.done(); }, 'Test From Style String': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(8); style.cssText = 'color: blue; background-color: red; width: 78%'; test.ok(3 === style.length, 'length is not 3'); test.ok('color: blue; background-color: red; width: 78%;' === style.cssText, 'cssText is wrong'); test.ok('blue' === style.getPropertyValue('color'), "getPropertyValue('color') failed"); test.ok('color' === style.item(0), 'item(0) failed'); test.ok('background-color' === style[1], 'style[1] failed'); test.ok('red' === style.backgroundColor, 'style.backgroundColor failed with "' + style.backgroundColor + '"'); style.cssText = ''; test.ok('' === style.cssText, 'cssText is not empty'); test.ok(0 === style.length, 'length is not 0'); test.done(); }, 'Test From Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(11); style.color = 'blue'; test.ok(1 === style.length, 'length is not 1'); test.ok('color' === style[0], 'style[0] is not color'); test.ok('color: blue;' === style.cssText, 'cssText is wrong'); test.ok('color' === style.item(0), 'item(0) is not color'); test.ok('blue' === style.color, 'color is not blue'); style.backgroundColor = 'red'; test.ok(2 === style.length, 'length is not 2'); test.ok('color' === style[0], 'style[0] is not color'); test.ok('background-color' === style[1], 'style[1] is not background-color'); test.ok('color: blue; background-color: red;' === style.cssText, 'cssText is wrong'); test.ok('red' === style.backgroundColor, 'backgroundColor is not red'); style.removeProperty('color'); test.ok('background-color' === style[0], 'style[0] is not background-color'); test.done(); }, 'Test Shorthand Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(11); style.background = 'blue url(path_to_url test.ok('blue' === style.backgroundColor, 'backgroundColor is not blue'); test.ok('url(path_to_url === style.backgroundImage, 'backgroundImage is wrong'); test.ok('blue url(path_to_url === style.background, 'background is different'); style.border = '0 solid black'; test.ok('0px' === style.borderWidth, 'borderWidth is not 0px'); test.ok('solid' === style.borderStyle, 'borderStyle is not solid'); test.ok('black' === style.borderColor, 'borderColor is not black'); test.ok('0px' === style.borderTopWidth, 'borderTopWidth is not 0px'); test.ok('solid' === style.borderLeftStyle, 'borderLeftStyle is not solid'); test.ok('black' === style.borderBottomColor, 'borderBottomColor is not black'); style.font = '12em monospace'; test.ok('12em' === style.fontSize, 'fontSize is not 12em'); test.ok('monospace' === style.fontFamily, 'fontFamily is not monospace'); test.done(); }, 'Test width and height Properties and null and empty strings': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(7); style.height = 6; test.ok('' === style.height, 'height does not remain unset'); style.width = 0; test.ok('0px' === style.width, 'width is not 0px'); style.height = '34%'; test.ok('34%' === style.height, 'height is not 34%'); style.height = ''; test.ok(style.length === 1, 'length is not 1'); test.ok('width: 0px;' === style.cssText, 'cssText is not "width: 0px;"'); style.width = null; test.ok(style.length === 0, 'length is not 0'); test.ok('' === style.cssText, 'cssText is not empty string'); test.done(); }, 'Test Implicit Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(7); style.borderWidth = 0; test.ok(1 === style.length, 'length is not 1'); test.ok('0px' === style.borderWidth, 'borderWidth is not 0px'); test.ok('0px' === style.borderTopWidth, 'borderTopWidth is not 0px'); test.ok('0px' === style.borderBottomWidth, 'borderBottomWidth is not 0px'); test.ok('0px' === style.borderLeftWidth, 'borderLeftWidth is not 0px'); test.ok('0px' === style.borderRightWidth, 'borderRightWidth is not 0px'); test.ok('border-width: 0px;' === style.cssText, 'cssText is not "border-width: 0px", "' + style.cssText + '"'); test.done(); }, 'Test Top, Left, Right, Bottom Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(6); style.top = 0; style.left = '0%'; style.right = '5em'; style.bottom = '12pt'; test.ok('0px' === style.top, 'top is not 0px'); test.ok('0%' === style.left, 'left is not 0%'); test.ok('5em' === style.right, 'right is not 5em'); test.ok('12pt' === style.bottom, 'bottom is not 12pt'); test.ok(4 === style.length, 'length is not 4'); test.ok('top: 0px; left: 0%; right: 5em; bottom: 12pt;' === style.cssText, 'text is not "top: 0px; left: 0%; right: 5em; bottom: 12pt;"'); test.done(); }, 'Test Clear and Clip Properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(10); style.clear = 'none'; test.ok('none' === style.clear, 'clear is not none'); style.clear = 'lfet'; // intentionally wrong test.ok('none' === style.clear, 'clear is not still none'); style.clear = 'left'; test.ok('left' === style.clear, 'clear is not left'); style.clear = 'right'; test.ok('right' === style.clear, 'clear is not right'); style.clear = 'both'; test.ok('both' === style.clear, 'clear is not both'); style.clip = 'elipse(5px, 10px)'; test.ok('' === style.clip, 'clip should not be set'); test.ok(1 === style.length, 'length is not 1'); style.clip = 'rect(0, 3Em, 2pt, 50%)'; test.ok('rect(0px, 3em, 2pt, 50%)' === style.clip, 'clip is not "rect(0px, 3em, 2pt, 50%)", "' + style.clip + '"'); test.ok(2 === style.length, 'length is not 2'); test.ok('clear: both; clip: rect(0px, 3em, 2pt, 50%);' === style.cssText, 'cssText is not "clear: both; clip: rect(0px, 3em, 2pt, 50%);"'); test.done(); }, 'Test colors': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(4); style.color = 'rgba(0,0,0,0)'; test.ok('rgba(0, 0, 0, 0)' === style.color, 'color is not rgba(0, 0, 0, 0)'); style.color = 'rgba(5%, 10%, 20%, 0.4)'; test.ok('rgba(12, 25, 51, 0.4)' === style.color, 'color is not rgba(12, 25, 51, 0.4)'); style.color = 'rgb(33%, 34%, 33%)'; test.ok('rgb(84, 86, 84)' === style.color, 'color is not rgb(84, 86, 84)'); style.color = 'rgba(300, 200, 100, 1.5)'; test.ok('rgb(255, 200, 100)' === style.color, 'color is not rgb(255, 200, 100) ' + style.color); test.done(); }, 'Test short hand properties with embedded spaces': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(4); style.background = 'rgb(0, 0, 0) url(/something/somewhere.jpg)'; test.ok('rgb(0, 0, 0)' === style.backgroundColor, 'backgroundColor is not rgb(0, 0, 0): ' + style.backgroundColor); test.ok('url(/something/somewhere.jpg)' === style.backgroundImage, 'backgroundImage is not url(/something/somewhere.jpg): ' + style.backgroundImage); test.ok('background: rgb(0, 0, 0) url(/something/somewhere.jpg);' === style.cssText, 'cssText is not correct: ' + style.cssText); style = new cssstyle.CSSStyleDeclaration(); style.border = ' 1px solid black '; test.ok('1px solid black' === style.border, 'multiple spaces not properly parsed: ' + style.border); test.done(); }, 'Setting shorthand properties to an empty string should clear all dependent properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(2); style.borderWidth = '1px'; test.ok('border-width: 1px;' === style.cssText, 'cssText is not "border-width: 1px;": ' + style.cssText); style.border = ''; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); test.done(); }, 'Setting implicit properties to an empty string should clear all dependent properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(2); style.borderTopWidth = '1px'; test.ok('border-top-width: 1px;' === style.cssText, 'cssText is not "border-top-width: 1px;": ' + style.cssText); style.borderWidth = ''; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); test.done(); }, 'Setting a shorthand property, whose shorthands are implicit properties, to an empty string should clear all dependent properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(4); style.borderTopWidth = '1px'; test.ok('border-top-width: 1px;' === style.cssText, 'cssText is not "border-top-width: 1px;": ' + style.cssText); style.border = ''; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); style.borderTop = '1px solid black'; test.ok('border-top: 1px solid black;' === style.cssText, 'cssText is not "border-top: 1px solid black;": ' + style.cssText); style.border = ''; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); test.done(); }, 'Setting border values to "none" should clear dependent values': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(8); style.borderTopWidth = '1px'; test.ok('border-top-width: 1px;' === style.cssText, 'cssText is not "border-top-width: 1px;": ' + style.cssText); style.border = 'none'; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); style.borderTopWidth = '1px'; test.ok('border-top-width: 1px;' === style.cssText, 'cssText is not "border-top-width: 1px;": ' + style.cssText); style.borderTopStyle = 'none'; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); style.borderTopWidth = '1px'; test.ok('border-top-width: 1px;' === style.cssText, 'cssText is not "border-top-width: 1px;": ' + style.cssText); style.borderTop = 'none'; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); style.borderTopWidth = '1px'; style.borderLeftWidth = '1px'; test.ok('border-top-width: 1px; border-left-width: 1px;' === style.cssText, 'cssText is not "border-top-width: 1px; border-left-width: 1px;": ' + style.cssText); style.borderTop = 'none'; test.ok('border-left-width: 1px;' === style.cssText, 'cssText is not "border-left-width: 1px;": ' + style.cssText); test.done(); }, 'Setting border to 0 should be okay': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(1); style.border = 0; test.ok('border: 0px;' === style.cssText, 'cssText is not "border: 0px;": ' + style.cssText); test.done(); }, 'Setting values implicit and shorthand properties via cssText and setProperty should propagate to dependent properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(4); style.cssText = 'border: 1px solid black;'; test.ok('border: 1px solid black;' === style.cssText, 'cssText is not "border: 1px solid black;": ' + style.cssText); test.ok('1px solid black' === style.borderTop, 'borderTop is not "1px solid black": ' + style.borderTop); style.border = ''; test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); style.setProperty('border', '1px solid black'); test.ok('border: 1px solid black;' === style.cssText, 'cssText is not "border: 1px solid black;": ' + style.cssText); test.done(); }, 'Setting opacity should work': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(3); style.setProperty('opacity', 0.75); test.ok('opacity: 0.75;' === style.cssText, 'cssText is not "opacity: 0.75;": ' + style.cssText); style.opacity = '0.50'; test.ok('opacity: 0.5;' === style.cssText, 'cssText is not "opacity: 0.5;": ' + style.cssText); style.opacity = 1.0; test.ok('opacity: 1;' === style.cssText, 'cssText is not "opacity: 1;": ' + style.cssText); test.done(); }, 'Width and height of auto should work': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(4); style.width = "auto"; test.equal(style.cssText,'width: auto;', 'cssText is not "width: auto;": ' + style.cssText); test.equal(style.width,'auto', 'width is not "auto": ' + style.width); style = new cssstyle.CSSStyleDeclaration(); style.height = "auto"; test.equal(style.cssText,'height: auto;', 'cssText is not "height: auto;": ' + style.cssText); test.equal(style.height,'auto', 'height is not "auto": ' + style.height); test.done(); }, 'Padding and margin should set/clear shorthand properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); var parts = ["Top","Right","Bottom","Left"]; var testParts = function (name,v,V) { style[name] = v; for (var i = 0; i < 4; i++) { var part = name + parts[i]; test.equal(V[i],style[part], part + ' is not "' + V[i] + '": "' + style[part] + '"'); } test.equal(v,style[name], name + ' is not "' + v + '": "' + style[name] + '"'); style[name] = ""; }; test.expect(50); testParts("padding","1px",["1px","1px","1px","1px"]); testParts("padding","1px 2%",["1px","2%","1px","2%"]); testParts("padding","1px 2px 3px",["1px","2px","3px","2px"]); testParts("padding","1px 2px 3px 4px",["1px","2px","3px","4px"]); style.paddingTop = style.paddingRight = style.paddingBottom = style.paddingLeft = "1px"; testParts("padding","",["","","",""]); testParts("margin","1px",["1px","1px","1px","1px"]); testParts("margin","1px auto",["1px","auto","1px","auto"]); testParts("margin","1px 2% 3px",["1px","2%","3px","2%"]); testParts("margin","1px 2px 3px 4px",["1px","2px","3px","4px"]); style.marginTop = style.marginRight = style.marginBottom = style.marginLeft = "1px"; testParts("margin","",["","","",""]); test.done(); }, 'Padding and margin shorthands should set main properties': function (test) { var style = new cssstyle.CSSStyleDeclaration(); var parts = ["Top","Right","Bottom","Left"]; var testParts = function (name,v,V) { var expect; for (var i = 0; i < 4; i++) { style[name] = v; style[name+parts[i]] = V; expect = v.split(/ /); expect[i] = V; expect = expect.join(" "); test.equal(expect,style[name], name + ' is not "' + expect + '": "' + style[name] + '"'); } }; test.expect(12); testParts("padding","1px 2px 3px 4px","10px"); testParts("margin","1px 2px 3px 4px","10px"); testParts("margin","1px 2px 3px 4px","auto"); test.done(); }, 'Setting a value to 0 should return the string value': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(1); style.setProperty('fill-opacity', 0); test.ok('0' === style.fillOpacity, 'fillOpacity is not "0": ' + style.fillOpacity); test.done(); }, 'onChange callback should be called when the cssText changes': function (test) { var style = new cssstyle.CSSStyleDeclaration(function (cssText) { test.ok('opacity: 0;' === cssText, 'cssText is not "opacity: 0;": ' + cssText); test.done(); }); test.expect(1); style.setProperty('opacity', 0); }, 'Setting float should work the same as cssFloat': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(1); style.float = 'left'; test.ok('left' === style.cssFloat, 'cssFloat is not "left": ' + style.cssFloat); test.done(); }, 'Setting improper css to cssText should not throw': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(2); style.cssText = 'color: '; test.ok('' === style.cssText, 'cssText wasn\'t cleared: ' + style.cssText); style.color = 'black'; style.cssText = 'float: '; test.ok('' === style.cssText, 'cssText wasn\'t cleared: ' + style.cssText); test.done(); }, 'Make sure url parsing works with quotes': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(3); style.backgroundImage = 'url(path_to_url test.ok('url(path_to_url === style.backgroundImage, 'background-image wasn\'t url(path_to_url ' + style.backgroundImage); style.backgroundImage = 'url(\'path_to_url test.ok('url(path_to_url === style.backgroundImage, 'background-image wasn\'t url(path_to_url ' + style.backgroundImage); style.backgroundImage = 'url("path_to_url")'; test.ok('url(path_to_url === style.backgroundImage, 'background-image wasn\'t url(path_to_url ' + style.backgroundImage); test.done(); }, 'Make sure setting 0 to a padding or margin works': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(2); style.padding = 0; test.equal(style.cssText, 'padding: 0px;', 'padding is not 0px'); style.margin = '1em'; style.marginTop = '0' test.equal(style.marginTop, '0px', 'margin-top is not 0px'); test.done(); }, 'Make sure setting null to background works': function (test) { var style = new cssstyle.CSSStyleDeclaration(); test.expect(2); style.background = 'red'; test.equal(style.cssText, 'background: red;', 'background is not red'); style.background = null; test.equal(style.cssText, '', 'cssText is not empty'); test.done(); } }; ```
/content/code_sandbox/node_modules/cssstyle/tests/tests.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
6,042
```javascript /********************************************************************* * This is a fork from the CSS Style Declaration part of * path_to_url ********************************************************************/ "use strict"; var CSSOM = require('cssom'); var fs = require('fs'); var path = require('path'); var camelToDashed = require('./parsers').camelToDashed; var dashedToCamelCase = require('./parsers').dashedToCamelCase; /** * @constructor * @see path_to_url#CSS-CSSStyleDeclaration */ var CSSStyleDeclaration = function CSSStyleDeclaration(onChangeCallback) { this._values = {}; this._importants = {}; this._length = 0; this._onChange = onChangeCallback || function () { return; }; }; CSSStyleDeclaration.prototype = { constructor: CSSStyleDeclaration, /** * * @param {string} name * @see path_to_url#CSS-CSSStyleDeclaration-getPropertyValue * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set. */ getPropertyValue: function (name) { if (!this._values.hasOwnProperty(name)) { return ""; } return this._values[name].toString(); }, /** * * @param {string} name * @param {string} value * @param {string} [priority=null] "important" or null * @see path_to_url#CSS-CSSStyleDeclaration-setProperty */ setProperty: function (name, value, priority) { if (value === undefined) { return; } if (value === null || value === '') { this.removeProperty(name); return; } var camel_case = dashedToCamelCase(name); this[camel_case] = value; this._importants[name] = priority; }, _setProperty: function (name, value, priority) { if (value === undefined) { return; } if (value === null || value === '') { this.removeProperty(name); return; } if (this._values[name]) { // Property already exist. Overwrite it. var index = Array.prototype.indexOf.call(this, name); if (index < 0) { this[this._length] = name; this._length++; } } else { // New property. this[this._length] = name; this._length++; } this._values[name] = value; this._importants[name] = priority; this._onChange(this.cssText); }, /** * * @param {string} name * @see path_to_url#CSS-CSSStyleDeclaration-removeProperty * @return {string} the value of the property if it has been explicitly set for this declaration block. * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. */ removeProperty: function (name) { if (!this._values.hasOwnProperty(name)) { return ""; } var prevValue = this._values[name]; delete this._values[name]; delete this._importants[name]; var index = Array.prototype.indexOf.call(this, name); if (index < 0) { return prevValue; } // That's what WebKit and Opera do Array.prototype.splice.call(this, index, 1); // That's what Firefox does //this[index] = "" this._onChange(this.cssText); return prevValue; }, /** * * @param {String} name */ getPropertyPriority: function (name) { return this._importants[name] || ""; }, getPropertyCSSValue: function () { //FIXME return; }, /** * element.style.overflow = "auto" * element.style.getPropertyShorthand("overflow-x") * -> "overflow" */ getPropertyShorthand: function () { //FIXME return; }, isPropertyImplicit: function () { //FIXME return; }, /** * path_to_url#CSS-CSSStyleDeclaration-item */ item: function (index) { index = parseInt(index, 10); if (index < 0 || index >= this._length) { return ''; } return this[index]; } }; Object.defineProperties(CSSStyleDeclaration.prototype, { cssText: { get: function () { var properties = []; var i; var name; var value; var priority; for (i = 0; i < this._length; i++) { name = this[i]; value = this.getPropertyValue(name); priority = this.getPropertyPriority(name); if (priority !== '') { priority = " !" + priority; } properties.push([name, ': ', value, priority, ';'].join('')); } return properties.join(' '); }, set: function (value) { var i; this._values = {}; Array.prototype.splice.call(this, 0, this._length); this._importants = {}; var dummyRule; try { dummyRule = CSSOM.parse('#bogus{' + value + '}').cssRules[0].style; } catch (err) { // malformed css, just return return; } var rule_length = dummyRule.length; var name; for (i = 0; i < rule_length; ++i) { name = dummyRule[i]; this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); } this._onChange(this.cssText); }, enumerable: true, configurable: true }, parentRule: { get: function () { return null; }, enumerable: true, configurable: true }, length: { get: function () { return this._length; }, /** * This deletes indices if the new length is less then the current * length. If the new length is more, it does nothing, the new indices * will be undefined until set. **/ set: function (value) { var i; for (i = value; i < this._length; i++) { delete this[i]; } this._length = value; }, enumerable: true, configurable: true }, 'float': { get: function () { return this.cssFloat; }, set: function (value) { this.cssFloat = value; }, enumerable: true, configurable: true } }); require('./properties')(CSSStyleDeclaration.prototype); exports.CSSStyleDeclaration = CSSStyleDeclaration; ```
/content/code_sandbox/node_modules/cssstyle/lib/CSSStyleDeclaration.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,462
```javascript (function webpackUniversalModuleDefinition(root, factory) { /* istanbul ignore next */ if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); /* istanbul ignore next */ else if(typeof exports === 'object') exports["esprima"] = factory(); else root["esprima"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /* istanbul ignore if */ /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* 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. */ Object.defineProperty(exports, "__esModule", { value: true }); var comment_handler_1 = __webpack_require__(1); var jsx_parser_1 = __webpack_require__(3); var parser_1 = __webpack_require__(8); var tokenizer_1 = __webpack_require__(15); function parse(code, options, delegate) { var commentHandler = null; var proxyDelegate = function (node, metadata) { if (delegate) { delegate(node, metadata); } if (commentHandler) { commentHandler.visit(node, metadata); } }; var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; var collectComment = false; if (options) { collectComment = (typeof options.comment === 'boolean' && options.comment); var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); if (collectComment || attachComment) { commentHandler = new comment_handler_1.CommentHandler(); commentHandler.attach = attachComment; options.comment = true; parserDelegate = proxyDelegate; } } var isModule = false; if (options && typeof options.sourceType === 'string') { isModule = (options.sourceType === 'module'); } var parser; if (options && typeof options.jsx === 'boolean' && options.jsx) { parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); } else { parser = new parser_1.Parser(code, options, parserDelegate); } var program = isModule ? parser.parseModule() : parser.parseScript(); var ast = program; if (collectComment && commentHandler) { ast.comments = commentHandler.comments; } if (parser.config.tokens) { ast.tokens = parser.tokens; } if (parser.config.tolerant) { ast.errors = parser.errorHandler.errors; } return ast; } exports.parse = parse; function parseModule(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = 'module'; return parse(code, parsingOptions, delegate); } exports.parseModule = parseModule; function parseScript(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = 'script'; return parse(code, parsingOptions, delegate); } exports.parseScript = parseScript; function tokenize(code, options, delegate) { var tokenizer = new tokenizer_1.Tokenizer(code, options); var tokens; tokens = []; try { while (true) { var token = tokenizer.getNextToken(); if (!token) { break; } if (delegate) { token = delegate(token); } tokens.push(token); } } catch (e) { tokenizer.errorHandler.tolerate(e); } if (tokenizer.errorHandler.tolerant) { tokens.errors = tokenizer.errors(); } return tokens; } exports.tokenize = tokenize; var syntax_1 = __webpack_require__(2); exports.Syntax = syntax_1.Syntax; // Sync with *.json manifests. exports.version = '4.0.1'; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var syntax_1 = __webpack_require__(2); var CommentHandler = (function () { function CommentHandler() { this.attach = false; this.comments = []; this.stack = []; this.leading = []; this.trailing = []; } CommentHandler.prototype.insertInnerComments = function (node, metadata) { // innnerComments for properties empty block // `function a() {/** comments **\/}` if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { var innerComments = []; for (var i = this.leading.length - 1; i >= 0; --i) { var entry = this.leading[i]; if (metadata.end.offset >= entry.start) { innerComments.unshift(entry.comment); this.leading.splice(i, 1); this.trailing.splice(i, 1); } } if (innerComments.length) { node.innerComments = innerComments; } } }; CommentHandler.prototype.findTrailingComments = function (metadata) { var trailingComments = []; if (this.trailing.length > 0) { for (var i = this.trailing.length - 1; i >= 0; --i) { var entry_1 = this.trailing[i]; if (entry_1.start >= metadata.end.offset) { trailingComments.unshift(entry_1.comment); } } this.trailing.length = 0; return trailingComments; } var entry = this.stack[this.stack.length - 1]; if (entry && entry.node.trailingComments) { var firstComment = entry.node.trailingComments[0]; if (firstComment && firstComment.range[0] >= metadata.end.offset) { trailingComments = entry.node.trailingComments; delete entry.node.trailingComments; } } return trailingComments; }; CommentHandler.prototype.findLeadingComments = function (metadata) { var leadingComments = []; var target; while (this.stack.length > 0) { var entry = this.stack[this.stack.length - 1]; if (entry && entry.start >= metadata.start.offset) { target = entry.node; this.stack.pop(); } else { break; } } if (target) { var count = target.leadingComments ? target.leadingComments.length : 0; for (var i = count - 1; i >= 0; --i) { var comment = target.leadingComments[i]; if (comment.range[1] <= metadata.start.offset) { leadingComments.unshift(comment); target.leadingComments.splice(i, 1); } } if (target.leadingComments && target.leadingComments.length === 0) { delete target.leadingComments; } return leadingComments; } for (var i = this.leading.length - 1; i >= 0; --i) { var entry = this.leading[i]; if (entry.start <= metadata.start.offset) { leadingComments.unshift(entry.comment); this.leading.splice(i, 1); } } return leadingComments; }; CommentHandler.prototype.visitNode = function (node, metadata) { if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { return; } this.insertInnerComments(node, metadata); var trailingComments = this.findTrailingComments(metadata); var leadingComments = this.findLeadingComments(metadata); if (leadingComments.length > 0) { node.leadingComments = leadingComments; } if (trailingComments.length > 0) { node.trailingComments = trailingComments; } this.stack.push({ node: node, start: metadata.start.offset }); }; CommentHandler.prototype.visitComment = function (node, metadata) { var type = (node.type[0] === 'L') ? 'Line' : 'Block'; var comment = { type: type, value: node.value }; if (node.range) { comment.range = node.range; } if (node.loc) { comment.loc = node.loc; } this.comments.push(comment); if (this.attach) { var entry = { comment: { type: type, value: node.value, range: [metadata.start.offset, metadata.end.offset] }, start: metadata.start.offset }; if (node.loc) { entry.comment.loc = node.loc; } node.type = type; this.leading.push(entry); this.trailing.push(entry); } }; CommentHandler.prototype.visit = function (node, metadata) { if (node.type === 'LineComment') { this.visitComment(node, metadata); } else if (node.type === 'BlockComment') { this.visitComment(node, metadata); } else if (this.attach) { this.visitNode(node, metadata); } }; return CommentHandler; }()); exports.CommentHandler = CommentHandler; /***/ }, /* 2 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Syntax = { AssignmentExpression: 'AssignmentExpression', AssignmentPattern: 'AssignmentPattern', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AwaitExpression: 'AwaitExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExportAllDeclaration: 'ExportAllDeclaration', ExportDefaultDeclaration: 'ExportDefaultDeclaration', ExportNamedDeclaration: 'ExportNamedDeclaration', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForOfStatement: 'ForOfStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MetaProperty: 'MetaProperty', MethodDefinition: 'MethodDefinition', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Program: 'Program', Property: 'Property', RestElement: 'RestElement', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', Super: 'Super', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', 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' }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* istanbul ignore next */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var character_1 = __webpack_require__(4); var JSXNode = __webpack_require__(5); var jsx_syntax_1 = __webpack_require__(6); var Node = __webpack_require__(7); var parser_1 = __webpack_require__(8); var token_1 = __webpack_require__(13); var xhtml_entities_1 = __webpack_require__(14); token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; token_1.TokenName[101 /* Text */] = 'JSXText'; // Fully qualified element name, e.g. <svg:path> returns "svg:path" function getQualifiedElementName(elementName) { var qualifiedName; switch (elementName.type) { case jsx_syntax_1.JSXSyntax.JSXIdentifier: var id = elementName; qualifiedName = id.name; break; case jsx_syntax_1.JSXSyntax.JSXNamespacedName: var ns = elementName; qualifiedName = getQualifiedElementName(ns.namespace) + ':' + getQualifiedElementName(ns.name); break; case jsx_syntax_1.JSXSyntax.JSXMemberExpression: var expr = elementName; qualifiedName = getQualifiedElementName(expr.object) + '.' + getQualifiedElementName(expr.property); break; /* istanbul ignore next */ default: break; } return qualifiedName; } var JSXParser = (function (_super) { __extends(JSXParser, _super); function JSXParser(code, options, delegate) { return _super.call(this, code, options, delegate) || this; } JSXParser.prototype.parsePrimaryExpression = function () { return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); }; JSXParser.prototype.startJSX = function () { // Unwind the scanner before the lookahead token. this.scanner.index = this.startMarker.index; this.scanner.lineNumber = this.startMarker.line; this.scanner.lineStart = this.startMarker.index - this.startMarker.column; }; JSXParser.prototype.finishJSX = function () { // Prime the next lookahead. this.nextToken(); }; JSXParser.prototype.reenterJSX = function () { this.startJSX(); this.expectJSX('}'); // Pop the closing '}' added from the lookahead. if (this.config.tokens) { this.tokens.pop(); } }; JSXParser.prototype.createJSXNode = function () { this.collectComments(); return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser.prototype.createJSXChildNode = function () { return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser.prototype.scanXHTMLEntity = function (quote) { var result = '&'; var valid = true; var terminated = false; var numeric = false; var hex = false; while (!this.scanner.eof() && valid && !terminated) { var ch = this.scanner.source[this.scanner.index]; if (ch === quote) { break; } terminated = (ch === ';'); result += ch; ++this.scanner.index; if (!terminated) { switch (result.length) { case 2: // e.g. '&#123;' numeric = (ch === '#'); break; case 3: if (numeric) { // e.g. '&#x41;' hex = (ch === 'x'); valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); numeric = numeric && !hex; } break; default: valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); break; } } } if (valid && terminated && result.length > 2) { // e.g. '&#x41;' becomes just '#x41' var str = result.substr(1, result.length - 2); if (numeric && str.length > 1) { result = String.fromCharCode(parseInt(str.substr(1), 10)); } else if (hex && str.length > 2) { result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); } else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { result = xhtml_entities_1.XHTMLEntities[str]; } } return result; }; // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. JSXParser.prototype.lexJSX = function () { var cp = this.scanner.source.charCodeAt(this.scanner.index); // < > / : = { } if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { var value = this.scanner.source[this.scanner.index++]; return { type: 7 /* Punctuator */, value: value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index - 1, end: this.scanner.index }; } // " ' if (cp === 34 || cp === 39) { var start = this.scanner.index; var quote = this.scanner.source[this.scanner.index++]; var str = ''; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index++]; if (ch === quote) { break; } else if (ch === '&') { str += this.scanXHTMLEntity(quote); } else { str += ch; } } return { type: 8 /* StringLiteral */, value: str, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } // ... or . if (cp === 46) { var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); var value = (n1 === 46 && n2 === 46) ? '...' : '.'; var start = this.scanner.index; this.scanner.index += value.length; return { type: 7 /* Punctuator */, value: value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } // ` if (cp === 96) { // Only placeholder, since it will be rescanned as a real assignment expression. return { type: 10 /* Template */, value: '', lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index, end: this.scanner.index }; } // Identifer can not contain backslash (char code 92). if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { var start = this.scanner.index; ++this.scanner.index; while (!this.scanner.eof()) { var ch = this.scanner.source.charCodeAt(this.scanner.index); if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { ++this.scanner.index; } else if (ch === 45) { // Hyphen (char code 45) can be part of an identifier. ++this.scanner.index; } else { break; } } var id = this.scanner.source.slice(start, this.scanner.index); return { type: 100 /* Identifier */, value: id, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; } return this.scanner.lex(); }; JSXParser.prototype.nextJSXToken = function () { this.collectComments(); this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var token = this.lexJSX(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; if (this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser.prototype.nextJSXText = function () { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var start = this.scanner.index; var text = ''; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index]; if (ch === '{' || ch === '<') { break; } ++this.scanner.index; text += ch; if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { ++this.scanner.lineNumber; if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { ++this.scanner.index; } this.scanner.lineStart = this.scanner.index; } } this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; var token = { type: 101 /* Text */, value: text, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: start, end: this.scanner.index }; if ((text.length > 0) && this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser.prototype.peekJSXToken = function () { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.lexJSX(); this.scanner.restoreState(state); return next; }; // Expect the next JSX token to match the specified punctuator. // If not, an exception will be thrown. JSXParser.prototype.expectJSX = function (value) { var token = this.nextJSXToken(); if (token.type !== 7 /* Punctuator */ || token.value !== value) { this.throwUnexpectedToken(token); } }; // Return true if the next JSX token matches the specified punctuator. JSXParser.prototype.matchJSX = function (value) { var next = this.peekJSXToken(); return next.type === 7 /* Punctuator */ && next.value === value; }; JSXParser.prototype.parseJSXIdentifier = function () { var node = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 100 /* Identifier */) { this.throwUnexpectedToken(token); } return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); }; JSXParser.prototype.parseJSXElementName = function () { var node = this.createJSXNode(); var elementName = this.parseJSXIdentifier(); if (this.matchJSX(':')) { var namespace = elementName; this.expectJSX(':'); var name_1 = this.parseJSXIdentifier(); elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); } else if (this.matchJSX('.')) { while (this.matchJSX('.')) { var object = elementName; this.expectJSX('.'); var property = this.parseJSXIdentifier(); elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); } } return elementName; }; JSXParser.prototype.parseJSXAttributeName = function () { var node = this.createJSXNode(); var attributeName; var identifier = this.parseJSXIdentifier(); if (this.matchJSX(':')) { var namespace = identifier; this.expectJSX(':'); var name_2 = this.parseJSXIdentifier(); attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); } else { attributeName = identifier; } return attributeName; }; JSXParser.prototype.parseJSXStringLiteralAttribute = function () { var node = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 8 /* StringLiteral */) { this.throwUnexpectedToken(token); } var raw = this.getTokenRaw(token); return this.finalize(node, new Node.Literal(token.value, raw)); }; JSXParser.prototype.parseJSXExpressionAttribute = function () { var node = this.createJSXNode(); this.expectJSX('{'); this.finishJSX(); if (this.match('}')) { this.tolerateError('JSX attributes must only be assigned a non-empty expression'); } var expression = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser.prototype.parseJSXAttributeValue = function () { return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); }; JSXParser.prototype.parseJSXNameValueAttribute = function () { var node = this.createJSXNode(); var name = this.parseJSXAttributeName(); var value = null; if (this.matchJSX('=')) { this.expectJSX('='); value = this.parseJSXAttributeValue(); } return this.finalize(node, new JSXNode.JSXAttribute(name, value)); }; JSXParser.prototype.parseJSXSpreadAttribute = function () { var node = this.createJSXNode(); this.expectJSX('{'); this.expectJSX('...'); this.finishJSX(); var argument = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); }; JSXParser.prototype.parseJSXAttributes = function () { var attributes = []; while (!this.matchJSX('/') && !this.matchJSX('>')) { var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute(); attributes.push(attribute); } return attributes; }; JSXParser.prototype.parseJSXOpeningElement = function () { var node = this.createJSXNode(); this.expectJSX('<'); var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX('/'); if (selfClosing) { this.expectJSX('/'); } this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser.prototype.parseJSXBoundaryElement = function () { var node = this.createJSXNode(); this.expectJSX('<'); if (this.matchJSX('/')) { this.expectJSX('/'); var name_3 = this.parseJSXElementName(); this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); } var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX('/'); if (selfClosing) { this.expectJSX('/'); } this.expectJSX('>'); return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser.prototype.parseJSXEmptyExpression = function () { var node = this.createJSXChildNode(); this.collectComments(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; return this.finalize(node, new JSXNode.JSXEmptyExpression()); }; JSXParser.prototype.parseJSXExpressionContainer = function () { var node = this.createJSXNode(); this.expectJSX('{'); var expression; if (this.matchJSX('}')) { expression = this.parseJSXEmptyExpression(); this.expectJSX('}'); } else { this.finishJSX(); expression = this.parseAssignmentExpression(); this.reenterJSX(); } return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser.prototype.parseJSXChildren = function () { var children = []; while (!this.scanner.eof()) { var node = this.createJSXChildNode(); var token = this.nextJSXText(); if (token.start < token.end) { var raw = this.getTokenRaw(token); var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); children.push(child); } if (this.scanner.source[this.scanner.index] === '{') { var container = this.parseJSXExpressionContainer(); children.push(container); } else { break; } } return children; }; JSXParser.prototype.parseComplexJSXElement = function (el) { var stack = []; while (!this.scanner.eof()) { el.children = el.children.concat(this.parseJSXChildren()); var node = this.createJSXChildNode(); var element = this.parseJSXBoundaryElement(); if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { var opening = element; if (opening.selfClosing) { var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); el.children.push(child); } else { stack.push(el); el = { node: node, opening: opening, closing: null, children: [] }; } } if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { el.closing = element; var open_1 = getQualifiedElementName(el.opening.name); var close_1 = getQualifiedElementName(el.closing.name); if (open_1 !== close_1) { this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); } if (stack.length > 0) { var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); el = stack[stack.length - 1]; el.children.push(child); stack.pop(); } else { break; } } } return el; }; JSXParser.prototype.parseJSXElement = function () { var node = this.createJSXNode(); var opening = this.parseJSXOpeningElement(); var children = []; var closing = null; if (!opening.selfClosing) { var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); children = el.children; closing = el.closing; } return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); }; JSXParser.prototype.parseJSXRoot = function () { // Pop the opening '<' added from the lookahead. if (this.config.tokens) { this.tokens.pop(); } this.startJSX(); var element = this.parseJSXElement(); this.finishJSX(); return element; }; JSXParser.prototype.isStartOfExpression = function () { return _super.prototype.isStartOfExpression.call(this) || this.match('<'); }; return JSXParser; }(parser_1.Parser)); exports.JSXParser = JSXParser; /***/ }, /* 4 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // See also tools/generate-unicode-regex.js. var Regex = { // Unicode v8.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, // Unicode v8.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; exports.Character = { /* tslint:disable:no-bitwise */ fromCodePoint: function (cp) { return (cp < 0x10000) ? String.fromCharCode(cp) : String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); }, // path_to_url#sec-white-space isWhiteSpace: function (cp) { return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); }, // path_to_url#sec-line-terminators isLineTerminator: function (cp) { return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); }, // path_to_url#sec-names-and-keywords isIdentifierStart: function (cp) { return (cp === 0x24) || (cp === 0x5F) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || (cp === 0x5C) || ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); }, isIdentifierPart: function (cp) { return (cp === 0x24) || (cp === 0x5F) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || (cp >= 0x30 && cp <= 0x39) || (cp === 0x5C) || ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); }, // path_to_url#sec-literals-numeric-literals isDecimalDigit: function (cp) { return (cp >= 0x30 && cp <= 0x39); // 0..9 }, isHexDigit: function (cp) { return (cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x46) || (cp >= 0x61 && cp <= 0x66); // a..f }, isOctalDigit: function (cp) { return (cp >= 0x30 && cp <= 0x37); // 0..7 } }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var jsx_syntax_1 = __webpack_require__(6); /* tslint:disable:max-classes-per-file */ var JSXClosingElement = (function () { function JSXClosingElement(name) { this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; this.name = name; } return JSXClosingElement; }()); exports.JSXClosingElement = JSXClosingElement; var JSXElement = (function () { function JSXElement(openingElement, children, closingElement) { this.type = jsx_syntax_1.JSXSyntax.JSXElement; this.openingElement = openingElement; this.children = children; this.closingElement = closingElement; } return JSXElement; }()); exports.JSXElement = JSXElement; var JSXEmptyExpression = (function () { function JSXEmptyExpression() { this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; } return JSXEmptyExpression; }()); exports.JSXEmptyExpression = JSXEmptyExpression; var JSXExpressionContainer = (function () { function JSXExpressionContainer(expression) { this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; this.expression = expression; } return JSXExpressionContainer; }()); exports.JSXExpressionContainer = JSXExpressionContainer; var JSXIdentifier = (function () { function JSXIdentifier(name) { this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; this.name = name; } return JSXIdentifier; }()); exports.JSXIdentifier = JSXIdentifier; var JSXMemberExpression = (function () { function JSXMemberExpression(object, property) { this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; this.object = object; this.property = property; } return JSXMemberExpression; }()); exports.JSXMemberExpression = JSXMemberExpression; var JSXAttribute = (function () { function JSXAttribute(name, value) { this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; this.name = name; this.value = value; } return JSXAttribute; }()); exports.JSXAttribute = JSXAttribute; var JSXNamespacedName = (function () { function JSXNamespacedName(namespace, name) { this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; this.namespace = namespace; this.name = name; } return JSXNamespacedName; }()); exports.JSXNamespacedName = JSXNamespacedName; var JSXOpeningElement = (function () { function JSXOpeningElement(name, selfClosing, attributes) { this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; this.name = name; this.selfClosing = selfClosing; this.attributes = attributes; } return JSXOpeningElement; }()); exports.JSXOpeningElement = JSXOpeningElement; var JSXSpreadAttribute = (function () { function JSXSpreadAttribute(argument) { this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; this.argument = argument; } return JSXSpreadAttribute; }()); exports.JSXSpreadAttribute = JSXSpreadAttribute; var JSXText = (function () { function JSXText(value, raw) { this.type = jsx_syntax_1.JSXSyntax.JSXText; this.value = value; this.raw = raw; } return JSXText; }()); exports.JSXText = JSXText; /***/ }, /* 6 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JSXSyntax = { JSXAttribute: 'JSXAttribute', JSXClosingElement: 'JSXClosingElement', JSXElement: 'JSXElement', JSXEmptyExpression: 'JSXEmptyExpression', JSXExpressionContainer: 'JSXExpressionContainer', JSXIdentifier: 'JSXIdentifier', JSXMemberExpression: 'JSXMemberExpression', JSXNamespacedName: 'JSXNamespacedName', JSXOpeningElement: 'JSXOpeningElement', JSXSpreadAttribute: 'JSXSpreadAttribute', JSXText: 'JSXText' }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var syntax_1 = __webpack_require__(2); /* tslint:disable:max-classes-per-file */ var ArrayExpression = (function () { function ArrayExpression(elements) { this.type = syntax_1.Syntax.ArrayExpression; this.elements = elements; } return ArrayExpression; }()); exports.ArrayExpression = ArrayExpression; var ArrayPattern = (function () { function ArrayPattern(elements) { this.type = syntax_1.Syntax.ArrayPattern; this.elements = elements; } return ArrayPattern; }()); exports.ArrayPattern = ArrayPattern; var ArrowFunctionExpression = (function () { function ArrowFunctionExpression(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = false; } return ArrowFunctionExpression; }()); exports.ArrowFunctionExpression = ArrowFunctionExpression; var AssignmentExpression = (function () { function AssignmentExpression(operator, left, right) { this.type = syntax_1.Syntax.AssignmentExpression; this.operator = operator; this.left = left; this.right = right; } return AssignmentExpression; }()); exports.AssignmentExpression = AssignmentExpression; var AssignmentPattern = (function () { function AssignmentPattern(left, right) { this.type = syntax_1.Syntax.AssignmentPattern; this.left = left; this.right = right; } return AssignmentPattern; }()); exports.AssignmentPattern = AssignmentPattern; var AsyncArrowFunctionExpression = (function () { function AsyncArrowFunctionExpression(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = true; } return AsyncArrowFunctionExpression; }()); exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; var AsyncFunctionDeclaration = (function () { function AsyncFunctionDeclaration(id, params, body) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionDeclaration; }()); exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; var AsyncFunctionExpression = (function () { function AsyncFunctionExpression(id, params, body) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionExpression; }()); exports.AsyncFunctionExpression = AsyncFunctionExpression; var AwaitExpression = (function () { function AwaitExpression(argument) { this.type = syntax_1.Syntax.AwaitExpression; this.argument = argument; } return AwaitExpression; }()); exports.AwaitExpression = AwaitExpression; var BinaryExpression = (function () { function BinaryExpression(operator, left, right) { var logical = (operator === '||' || operator === '&&'); this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; this.operator = operator; this.left = left; this.right = right; } return BinaryExpression; }()); exports.BinaryExpression = BinaryExpression; var BlockStatement = (function () { function BlockStatement(body) { this.type = syntax_1.Syntax.BlockStatement; this.body = body; } return BlockStatement; }()); exports.BlockStatement = BlockStatement; var BreakStatement = (function () { function BreakStatement(label) { this.type = syntax_1.Syntax.BreakStatement; this.label = label; } return BreakStatement; }()); exports.BreakStatement = BreakStatement; var CallExpression = (function () { function CallExpression(callee, args) { this.type = syntax_1.Syntax.CallExpression; this.callee = callee; this.arguments = args; } return CallExpression; }()); exports.CallExpression = CallExpression; var CatchClause = (function () { function CatchClause(param, body) { this.type = syntax_1.Syntax.CatchClause; this.param = param; this.body = body; } return CatchClause; }()); exports.CatchClause = CatchClause; var ClassBody = (function () { function ClassBody(body) { this.type = syntax_1.Syntax.ClassBody; this.body = body; } return ClassBody; }()); exports.ClassBody = ClassBody; var ClassDeclaration = (function () { function ClassDeclaration(id, superClass, body) { this.type = syntax_1.Syntax.ClassDeclaration; this.id = id; this.superClass = superClass; this.body = body; } return ClassDeclaration; }()); exports.ClassDeclaration = ClassDeclaration; var ClassExpression = (function () { function ClassExpression(id, superClass, body) { this.type = syntax_1.Syntax.ClassExpression; this.id = id; this.superClass = superClass; this.body = body; } return ClassExpression; }()); exports.ClassExpression = ClassExpression; var ComputedMemberExpression = (function () { function ComputedMemberExpression(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = true; this.object = object; this.property = property; } return ComputedMemberExpression; }()); exports.ComputedMemberExpression = ComputedMemberExpression; var ConditionalExpression = (function () { function ConditionalExpression(test, consequent, alternate) { this.type = syntax_1.Syntax.ConditionalExpression; this.test = test; this.consequent = consequent; this.alternate = alternate; } return ConditionalExpression; }()); exports.ConditionalExpression = ConditionalExpression; var ContinueStatement = (function () { function ContinueStatement(label) { this.type = syntax_1.Syntax.ContinueStatement; this.label = label; } return ContinueStatement; }()); exports.ContinueStatement = ContinueStatement; var DebuggerStatement = (function () { function DebuggerStatement() { this.type = syntax_1.Syntax.DebuggerStatement; } return DebuggerStatement; }()); exports.DebuggerStatement = DebuggerStatement; var Directive = (function () { function Directive(expression, directive) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; this.directive = directive; } return Directive; }()); exports.Directive = Directive; var DoWhileStatement = (function () { function DoWhileStatement(body, test) { this.type = syntax_1.Syntax.DoWhileStatement; this.body = body; this.test = test; } return DoWhileStatement; }()); exports.DoWhileStatement = DoWhileStatement; var EmptyStatement = (function () { function EmptyStatement() { this.type = syntax_1.Syntax.EmptyStatement; } return EmptyStatement; }()); exports.EmptyStatement = EmptyStatement; var ExportAllDeclaration = (function () { function ExportAllDeclaration(source) { this.type = syntax_1.Syntax.ExportAllDeclaration; this.source = source; } return ExportAllDeclaration; }()); exports.ExportAllDeclaration = ExportAllDeclaration; var ExportDefaultDeclaration = (function () { function ExportDefaultDeclaration(declaration) { this.type = syntax_1.Syntax.ExportDefaultDeclaration; this.declaration = declaration; } return ExportDefaultDeclaration; }()); exports.ExportDefaultDeclaration = ExportDefaultDeclaration; var ExportNamedDeclaration = (function () { function ExportNamedDeclaration(declaration, specifiers, source) { this.type = syntax_1.Syntax.ExportNamedDeclaration; this.declaration = declaration; this.specifiers = specifiers; this.source = source; } return ExportNamedDeclaration; }()); exports.ExportNamedDeclaration = ExportNamedDeclaration; var ExportSpecifier = (function () { function ExportSpecifier(local, exported) { this.type = syntax_1.Syntax.ExportSpecifier; this.exported = exported; this.local = local; } return ExportSpecifier; }()); exports.ExportSpecifier = ExportSpecifier; var ExpressionStatement = (function () { function ExpressionStatement(expression) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; } return ExpressionStatement; }()); exports.ExpressionStatement = ExpressionStatement; var ForInStatement = (function () { function ForInStatement(left, right, body) { this.type = syntax_1.Syntax.ForInStatement; this.left = left; this.right = right; this.body = body; this.each = false; } return ForInStatement; }()); exports.ForInStatement = ForInStatement; var ForOfStatement = (function () { function ForOfStatement(left, right, body) { this.type = syntax_1.Syntax.ForOfStatement; this.left = left; this.right = right; this.body = body; } return ForOfStatement; }()); exports.ForOfStatement = ForOfStatement; var ForStatement = (function () { function ForStatement(init, test, update, body) { this.type = syntax_1.Syntax.ForStatement; this.init = init; this.test = test; this.update = update; this.body = body; } return ForStatement; }()); exports.ForStatement = ForStatement; var FunctionDeclaration = (function () { function FunctionDeclaration(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionDeclaration; }()); exports.FunctionDeclaration = FunctionDeclaration; var FunctionExpression = (function () { function FunctionExpression(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionExpression; }()); exports.FunctionExpression = FunctionExpression; var Identifier = (function () { function Identifier(name) { this.type = syntax_1.Syntax.Identifier; this.name = name; } return Identifier; }()); exports.Identifier = Identifier; var IfStatement = (function () { function IfStatement(test, consequent, alternate) { this.type = syntax_1.Syntax.IfStatement; this.test = test; this.consequent = consequent; this.alternate = alternate; } return IfStatement; }()); exports.IfStatement = IfStatement; var ImportDeclaration = (function () { function ImportDeclaration(specifiers, source) { this.type = syntax_1.Syntax.ImportDeclaration; this.specifiers = specifiers; this.source = source; } return ImportDeclaration; }()); exports.ImportDeclaration = ImportDeclaration; var ImportDefaultSpecifier = (function () { function ImportDefaultSpecifier(local) { this.type = syntax_1.Syntax.ImportDefaultSpecifier; this.local = local; } return ImportDefaultSpecifier; }()); exports.ImportDefaultSpecifier = ImportDefaultSpecifier; var ImportNamespaceSpecifier = (function () { function ImportNamespaceSpecifier(local) { this.type = syntax_1.Syntax.ImportNamespaceSpecifier; this.local = local; } return ImportNamespaceSpecifier; }()); exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; var ImportSpecifier = (function () { function ImportSpecifier(local, imported) { this.type = syntax_1.Syntax.ImportSpecifier; this.local = local; this.imported = imported; } return ImportSpecifier; }()); exports.ImportSpecifier = ImportSpecifier; var LabeledStatement = (function () { function LabeledStatement(label, body) { this.type = syntax_1.Syntax.LabeledStatement; this.label = label; this.body = body; } return LabeledStatement; }()); exports.LabeledStatement = LabeledStatement; var Literal = (function () { function Literal(value, raw) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; } return Literal; }()); exports.Literal = Literal; var MetaProperty = (function () { function MetaProperty(meta, property) { this.type = syntax_1.Syntax.MetaProperty; this.meta = meta; this.property = property; } return MetaProperty; }()); exports.MetaProperty = MetaProperty; var MethodDefinition = (function () { function MethodDefinition(key, computed, value, kind, isStatic) { this.type = syntax_1.Syntax.MethodDefinition; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.static = isStatic; } return MethodDefinition; }()); exports.MethodDefinition = MethodDefinition; var Module = (function () { function Module(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = 'module'; } return Module; }()); exports.Module = Module; var NewExpression = (function () { function NewExpression(callee, args) { this.type = syntax_1.Syntax.NewExpression; this.callee = callee; this.arguments = args; } return NewExpression; }()); exports.NewExpression = NewExpression; var ObjectExpression = (function () { function ObjectExpression(properties) { this.type = syntax_1.Syntax.ObjectExpression; this.properties = properties; } return ObjectExpression; }()); exports.ObjectExpression = ObjectExpression; var ObjectPattern = (function () { function ObjectPattern(properties) { this.type = syntax_1.Syntax.ObjectPattern; this.properties = properties; } return ObjectPattern; }()); exports.ObjectPattern = ObjectPattern; var Property = (function () { function Property(kind, key, computed, value, method, shorthand) { this.type = syntax_1.Syntax.Property; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.method = method; this.shorthand = shorthand; } return Property; }()); exports.Property = Property; var RegexLiteral = (function () { function RegexLiteral(value, raw, pattern, flags) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; this.regex = { pattern: pattern, flags: flags }; } return RegexLiteral; }()); exports.RegexLiteral = RegexLiteral; var RestElement = (function () { function RestElement(argument) { this.type = syntax_1.Syntax.RestElement; this.argument = argument; } return RestElement; }()); exports.RestElement = RestElement; var ReturnStatement = (function () { function ReturnStatement(argument) { this.type = syntax_1.Syntax.ReturnStatement; this.argument = argument; } return ReturnStatement; }()); exports.ReturnStatement = ReturnStatement; var Script = (function () { function Script(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = 'script'; } return Script; }()); exports.Script = Script; var SequenceExpression = (function () { function SequenceExpression(expressions) { this.type = syntax_1.Syntax.SequenceExpression; this.expressions = expressions; } return SequenceExpression; }()); exports.SequenceExpression = SequenceExpression; var SpreadElement = (function () { function SpreadElement(argument) { this.type = syntax_1.Syntax.SpreadElement; this.argument = argument; } return SpreadElement; }()); exports.SpreadElement = SpreadElement; var StaticMemberExpression = (function () { function StaticMemberExpression(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = false; this.object = object; this.property = property; } return StaticMemberExpression; }()); exports.StaticMemberExpression = StaticMemberExpression; var Super = (function () { function Super() { this.type = syntax_1.Syntax.Super; } return Super; }()); exports.Super = Super; var SwitchCase = (function () { function SwitchCase(test, consequent) { this.type = syntax_1.Syntax.SwitchCase; this.test = test; this.consequent = consequent; } return SwitchCase; }()); exports.SwitchCase = SwitchCase; var SwitchStatement = (function () { function SwitchStatement(discriminant, cases) { this.type = syntax_1.Syntax.SwitchStatement; this.discriminant = discriminant; this.cases = cases; } return SwitchStatement; }()); exports.SwitchStatement = SwitchStatement; var TaggedTemplateExpression = (function () { function TaggedTemplateExpression(tag, quasi) { this.type = syntax_1.Syntax.TaggedTemplateExpression; this.tag = tag; this.quasi = quasi; } return TaggedTemplateExpression; }()); exports.TaggedTemplateExpression = TaggedTemplateExpression; var TemplateElement = (function () { function TemplateElement(value, tail) { this.type = syntax_1.Syntax.TemplateElement; this.value = value; this.tail = tail; } return TemplateElement; }()); exports.TemplateElement = TemplateElement; var TemplateLiteral = (function () { function TemplateLiteral(quasis, expressions) { this.type = syntax_1.Syntax.TemplateLiteral; this.quasis = quasis; this.expressions = expressions; } return TemplateLiteral; }()); exports.TemplateLiteral = TemplateLiteral; var ThisExpression = (function () { function ThisExpression() { this.type = syntax_1.Syntax.ThisExpression; } return ThisExpression; }()); exports.ThisExpression = ThisExpression; var ThrowStatement = (function () { function ThrowStatement(argument) { this.type = syntax_1.Syntax.ThrowStatement; this.argument = argument; } return ThrowStatement; }()); exports.ThrowStatement = ThrowStatement; var TryStatement = (function () { function TryStatement(block, handler, finalizer) { this.type = syntax_1.Syntax.TryStatement; this.block = block; this.handler = handler; this.finalizer = finalizer; } return TryStatement; }()); exports.TryStatement = TryStatement; var UnaryExpression = (function () { function UnaryExpression(operator, argument) { this.type = syntax_1.Syntax.UnaryExpression; this.operator = operator; this.argument = argument; this.prefix = true; } return UnaryExpression; }()); exports.UnaryExpression = UnaryExpression; var UpdateExpression = (function () { function UpdateExpression(operator, argument, prefix) { this.type = syntax_1.Syntax.UpdateExpression; this.operator = operator; this.argument = argument; this.prefix = prefix; } return UpdateExpression; }()); exports.UpdateExpression = UpdateExpression; var VariableDeclaration = (function () { function VariableDeclaration(declarations, kind) { this.type = syntax_1.Syntax.VariableDeclaration; this.declarations = declarations; this.kind = kind; } return VariableDeclaration; }()); exports.VariableDeclaration = VariableDeclaration; var VariableDeclarator = (function () { function VariableDeclarator(id, init) { this.type = syntax_1.Syntax.VariableDeclarator; this.id = id; this.init = init; } return VariableDeclarator; }()); exports.VariableDeclarator = VariableDeclarator; var WhileStatement = (function () { function WhileStatement(test, body) { this.type = syntax_1.Syntax.WhileStatement; this.test = test; this.body = body; } return WhileStatement; }()); exports.WhileStatement = WhileStatement; var WithStatement = (function () { function WithStatement(object, body) { this.type = syntax_1.Syntax.WithStatement; this.object = object; this.body = body; } return WithStatement; }()); exports.WithStatement = WithStatement; var YieldExpression = (function () { function YieldExpression(argument, delegate) { this.type = syntax_1.Syntax.YieldExpression; this.argument = argument; this.delegate = delegate; } return YieldExpression; }()); exports.YieldExpression = YieldExpression; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var assert_1 = __webpack_require__(9); var error_handler_1 = __webpack_require__(10); var messages_1 = __webpack_require__(11); var Node = __webpack_require__(7); var scanner_1 = __webpack_require__(12); var syntax_1 = __webpack_require__(2); var token_1 = __webpack_require__(13); var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; var Parser = (function () { function Parser(code, options, delegate) { if (options === void 0) { options = {}; } this.config = { range: (typeof options.range === 'boolean') && options.range, loc: (typeof options.loc === 'boolean') && options.loc, source: null, tokens: (typeof options.tokens === 'boolean') && options.tokens, comment: (typeof options.comment === 'boolean') && options.comment, tolerant: (typeof options.tolerant === 'boolean') && options.tolerant }; if (this.config.loc && options.source && options.source !== null) { this.config.source = String(options.source); } this.delegate = delegate; this.errorHandler = new error_handler_1.ErrorHandler(); this.errorHandler.tolerant = this.config.tolerant; this.scanner = new scanner_1.Scanner(code, this.errorHandler); this.scanner.trackComment = this.config.comment; this.operatorPrecedence = { ')': 0, ';': 0, ',': 0, '=': 0, ']': 0, '||': 1, '&&': 2, '|': 3, '^': 4, '&': 5, '==': 6, '!=': 6, '===': 6, '!==': 6, '<': 7, '>': 7, '<=': 7, '>=': 7, '<<': 8, '>>': 8, '>>>': 8, '+': 9, '-': 9, '*': 11, '/': 11, '%': 11 }; this.lookahead = { type: 2 /* EOF */, value: '', lineNumber: this.scanner.lineNumber, lineStart: 0, start: 0, end: 0 }; this.hasLineTerminator = false; this.context = { isModule: false, await: false, allowIn: true, allowStrictDirective: true, allowYield: true, firstCoverInitializedNameError: null, isAssignmentTarget: false, isBindingElement: false, inFunctionBody: false, inIteration: false, inSwitch: false, labelSet: {}, strict: false }; this.tokens = []; this.startMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.lastMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.nextToken(); this.lastMarker = { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; } Parser.prototype.throwError = function (messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert_1.assert(idx < args.length, 'Message reference must be in range'); return args[idx]; }); var index = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; throw this.errorHandler.createError(index, line, column, msg); }; Parser.prototype.tolerateError = function (messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert_1.assert(idx < args.length, 'Message reference must be in range'); return args[idx]; }); var index = this.lastMarker.index; var line = this.scanner.lineNumber; var column = this.lastMarker.column + 1; this.errorHandler.tolerateError(index, line, column, msg); }; // Throw an exception because of the token. Parser.prototype.unexpectedTokenError = function (token, message) { var msg = message || messages_1.Messages.UnexpectedToken; var value; if (token) { if (!message) { msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken; if (token.type === 4 /* Keyword */) { if (this.scanner.isFutureReservedWord(token.value)) { msg = messages_1.Messages.UnexpectedReserved; } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { msg = messages_1.Messages.StrictReservedWord; } } } value = token.value; } else { value = 'ILLEGAL'; } msg = msg.replace('%0', value); if (token && typeof token.lineNumber === 'number') { var index = token.start; var line = token.lineNumber; var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; var column = token.start - lastMarkerLineStart + 1; return this.errorHandler.createError(index, line, column, msg); } else { var index = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; return this.errorHandler.createError(index, line, column, msg); } }; Parser.prototype.throwUnexpectedToken = function (token, message) { throw this.unexpectedTokenError(token, message); }; Parser.prototype.tolerateUnexpectedToken = function (token, message) { this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); }; Parser.prototype.collectComments = function () { if (!this.config.comment) { this.scanner.scanComments(); } else { var comments = this.scanner.scanComments(); if (comments.length > 0 && this.delegate) { for (var i = 0; i < comments.length; ++i) { var e = comments[i]; var node = void 0; node = { type: e.multiLine ? 'BlockComment' : 'LineComment', value: this.scanner.source.slice(e.slice[0], e.slice[1]) }; if (this.config.range) { node.range = e.range; } if (this.config.loc) { node.loc = e.loc; } var metadata = { start: { line: e.loc.start.line, column: e.loc.start.column, offset: e.range[0] }, end: { line: e.loc.end.line, column: e.loc.end.column, offset: e.range[1] } }; this.delegate(node, metadata); } } } }; // From internal representation to an external structure Parser.prototype.getTokenRaw = function (token) { return this.scanner.source.slice(token.start, token.end); }; Parser.prototype.convertToken = function (token) { var t = { type: token_1.TokenName[token.type], value: this.getTokenRaw(token) }; if (this.config.range) { t.range = [token.start, token.end]; } if (this.config.loc) { t.loc = { start: { line: this.startMarker.line, column: this.startMarker.column }, end: { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart } }; } if (token.type === 9 /* RegularExpression */) { var pattern = token.pattern; var flags = token.flags; t.regex = { pattern: pattern, flags: flags }; } return t; }; Parser.prototype.nextToken = function () { var token = this.lookahead; this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; this.collectComments(); if (this.scanner.index !== this.startMarker.index) { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; } var next = this.scanner.lex(); this.hasLineTerminator = (token.lineNumber !== next.lineNumber); if (next && this.context.strict && next.type === 3 /* Identifier */) { if (this.scanner.isStrictModeReservedWord(next.value)) { next.type = 4 /* Keyword */; } } this.lookahead = next; if (this.config.tokens && next.type !== 2 /* EOF */) { this.tokens.push(this.convertToken(next)); } return token; }; Parser.prototype.nextRegexToken = function () { this.collectComments(); var token = this.scanner.scanRegExp(); if (this.config.tokens) { // Pop the previous token, '/' or '/=' // This is added from the lookahead token. this.tokens.pop(); this.tokens.push(this.convertToken(token)); } // Prime the next lookahead. this.lookahead = token; this.nextToken(); return token; }; Parser.prototype.createNode = function () { return { index: this.startMarker.index, line: this.startMarker.line, column: this.startMarker.column }; }; Parser.prototype.startNode = function (token, lastLineStart) { if (lastLineStart === void 0) { lastLineStart = 0; } var column = token.start - token.lineStart; var line = token.lineNumber; if (column < 0) { column += lastLineStart; line--; } return { index: token.start, line: line, column: column }; }; Parser.prototype.finalize = function (marker, node) { if (this.config.range) { node.range = [marker.index, this.lastMarker.index]; } if (this.config.loc) { node.loc = { start: { line: marker.line, column: marker.column, }, end: { line: this.lastMarker.line, column: this.lastMarker.column } }; if (this.config.source) { node.loc.source = this.config.source; } } if (this.delegate) { var metadata = { start: { line: marker.line, column: marker.column, offset: marker.index }, end: { line: this.lastMarker.line, column: this.lastMarker.column, offset: this.lastMarker.index } }; this.delegate(node, metadata); } return node; }; // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. Parser.prototype.expect = function (value) { var token = this.nextToken(); if (token.type !== 7 /* Punctuator */ || token.value !== value) { this.throwUnexpectedToken(token); } }; // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). Parser.prototype.expectCommaSeparator = function () { if (this.config.tolerant) { var token = this.lookahead; if (token.type === 7 /* Punctuator */ && token.value === ',') { this.nextToken(); } else if (token.type === 7 /* Punctuator */ && token.value === ';') { this.nextToken(); this.tolerateUnexpectedToken(token); } else { this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); } } else { this.expect(','); } }; // Expect the next token to match the specified keyword. // If not, an exception will be thrown. Parser.prototype.expectKeyword = function (keyword) { var token = this.nextToken(); if (token.type !== 4 /* Keyword */ || token.value !== keyword) { this.throwUnexpectedToken(token); } }; // Return true if the next token matches the specified punctuator. Parser.prototype.match = function (value) { return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; }; // Return true if the next token matches the specified keyword Parser.prototype.matchKeyword = function (keyword) { return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; }; // Return true if the next token matches the specified contextual keyword // (where an identifier is sometimes a keyword depending on the context) Parser.prototype.matchContextualKeyword = function (keyword) { return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; }; // Return true if the next token is an assignment operator Parser.prototype.matchAssign = function () { if (this.lookahead.type !== 7 /* Punctuator */) { return false; } var op = this.lookahead.value; return op === '=' || op === '*=' || op === '**=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; }; // Cover grammar support. // // When an assignment expression position starts with an left parenthesis, the determination of the type // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) // or the first comma. This situation also defers the determination of all the expressions nested in the pair. // // There are three productions that can be parsed in a parentheses pair that needs to be determined // after the outermost pair is closed. They are: // // 1. AssignmentExpression // 2. BindingElements // 3. AssignmentTargets // // In order to avoid exponential backtracking, we use two flags to denote if the production can be // binding element or assignment target. // // The three productions have the relationship: // // BindingElements AssignmentTargets AssignmentExpression // // with a single exception that CoverInitializedName when used directly in an Expression, generates // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. // // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not // effect the current flags. This means the production the parser parses is only used as an expression. Therefore // the CoverInitializedName check is conducted. // // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates // the flags outside of the parser. This means the production the parser parses is used as a part of a potential // pattern. The CoverInitializedName check is deferred. Parser.prototype.isolateCoverGrammar = function (parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); if (this.context.firstCoverInitializedNameError !== null) { this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); } this.context.isBindingElement = previousIsBindingElement; this.context.isAssignmentTarget = previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; return result; }; Parser.prototype.inheritCoverGrammar = function (parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; return result; }; Parser.prototype.consumeSemicolon = function () { if (this.match(';')) { this.nextToken(); } else if (!this.hasLineTerminator) { if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { this.throwUnexpectedToken(this.lookahead); } this.lastMarker.index = this.startMarker.index; this.lastMarker.line = this.startMarker.line; this.lastMarker.column = this.startMarker.column; } }; // path_to_url#sec-primary-expression Parser.prototype.parsePrimaryExpression = function () { var node = this.createNode(); var expr; var token, raw; switch (this.lookahead.type) { case 3 /* Identifier */: if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { this.tolerateUnexpectedToken(this.lookahead); } expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); break; case 6 /* NumericLiteral */: case 8 /* StringLiteral */: if (this.context.strict && this.lookahead.octal) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(token.value, raw)); break; case 1 /* BooleanLiteral */: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); break; case 5 /* NullLiteral */: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.Literal(null, raw)); break; case 10 /* Template */: expr = this.parseTemplateLiteral(); break; case 7 /* Punctuator */: switch (this.lookahead.value) { case '(': this.context.isBindingElement = false; expr = this.inheritCoverGrammar(this.parseGroupExpression); break; case '[': expr = this.inheritCoverGrammar(this.parseArrayInitializer); break; case '{': expr = this.inheritCoverGrammar(this.parseObjectInitializer); break; case '/': case '/=': this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.scanner.index = this.startMarker.index; token = this.nextRegexToken(); raw = this.getTokenRaw(token); expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); break; default: expr = this.throwUnexpectedToken(this.nextToken()); } break; case 4 /* Keyword */: if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { expr = this.parseIdentifierName(); } else if (!this.context.strict && this.matchKeyword('let')) { expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); } else { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; if (this.matchKeyword('function')) { expr = this.parseFunctionExpression(); } else if (this.matchKeyword('this')) { this.nextToken(); expr = this.finalize(node, new Node.ThisExpression()); } else if (this.matchKeyword('class')) { expr = this.parseClassExpression(); } else { expr = this.throwUnexpectedToken(this.nextToken()); } } break; default: expr = this.throwUnexpectedToken(this.nextToken()); } return expr; }; // path_to_url#sec-array-initializer Parser.prototype.parseSpreadElement = function () { var node = this.createNode(); this.expect('...'); var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); return this.finalize(node, new Node.SpreadElement(arg)); }; Parser.prototype.parseArrayInitializer = function () { var node = this.createNode(); var elements = []; this.expect('['); while (!this.match(']')) { if (this.match(',')) { this.nextToken(); elements.push(null); } else if (this.match('...')) { var element = this.parseSpreadElement(); if (!this.match(']')) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.expect(','); } elements.push(element); } else { elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); if (!this.match(']')) { this.expect(','); } } } this.expect(']'); return this.finalize(node, new Node.ArrayExpression(elements)); }; // path_to_url#sec-object-initializer Parser.prototype.parsePropertyMethod = function (params) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = params.simple; var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); if (this.context.strict && params.firstRestricted) { this.tolerateUnexpectedToken(params.firstRestricted, params.message); } if (this.context.strict && params.stricted) { this.tolerateUnexpectedToken(params.stricted, params.message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; return body; }; Parser.prototype.parsePropertyMethodFunction = function () { var isGenerator = false; var node = this.createNode(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; Parser.prototype.parsePropertyMethodAsyncFunction = function () { var node = this.createNode(); var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = false; this.context.await = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; this.context.await = previousAwait; return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); }; Parser.prototype.parseObjectPropertyKey = function () { var node = this.createNode(); var token = this.nextToken(); var key; switch (token.type) { case 8 /* StringLiteral */: case 6 /* NumericLiteral */: if (this.context.strict && token.octal) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); } var raw = this.getTokenRaw(token); key = this.finalize(node, new Node.Literal(token.value, raw)); break; case 3 /* Identifier */: case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 4 /* Keyword */: key = this.finalize(node, new Node.Identifier(token.value)); break; case 7 /* Punctuator */: if (token.value === '[') { key = this.isolateCoverGrammar(this.parseAssignmentExpression); this.expect(']'); } else { key = this.throwUnexpectedToken(token); } break; default: key = this.throwUnexpectedToken(token); } return key; }; Parser.prototype.isPropertyKey = function (key, value) { return (key.type === syntax_1.Syntax.Identifier && key.name === value) || (key.type === syntax_1.Syntax.Literal && key.value === value); }; Parser.prototype.parseObjectProperty = function (hasProto) { var node = this.createNode(); var token = this.lookahead; var kind; var key = null; var value = null; var computed = false; var method = false; var shorthand = false; var isAsync = false; if (token.type === 3 /* Identifier */) { var id = token.value; this.nextToken(); computed = this.match('['); isAsync = !this.hasLineTerminator && (id === 'async') && !this.match(':') && !this.match('(') && !this.match('*') && !this.match(','); key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); } else if (this.match('*')) { this.nextToken(); } else { computed = this.match('['); key = this.parseObjectPropertyKey(); } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { kind = 'get'; computed = this.match('['); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { kind = 'set'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { kind = 'init'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } else { if (!key) { this.throwUnexpectedToken(this.lookahead); } kind = 'init'; if (this.match(':') && !isAsync) { if (!computed && this.isPropertyKey(key, '__proto__')) { if (hasProto.value) { this.tolerateError(messages_1.Messages.DuplicateProtoProperty); } hasProto.value = true; } this.nextToken(); value = this.inheritCoverGrammar(this.parseAssignmentExpression); } else if (this.match('(')) { value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } else if (token.type === 3 /* Identifier */) { var id = this.finalize(node, new Node.Identifier(token.value)); if (this.match('=')) { this.context.firstCoverInitializedNameError = this.lookahead; this.nextToken(); shorthand = true; var init = this.isolateCoverGrammar(this.parseAssignmentExpression); value = this.finalize(node, new Node.AssignmentPattern(id, init)); } else { shorthand = true; value = id; } } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); }; Parser.prototype.parseObjectInitializer = function () { var node = this.createNode(); this.expect('{'); var properties = []; var hasProto = { value: false }; while (!this.match('}')) { properties.push(this.parseObjectProperty(hasProto)); if (!this.match('}')) { this.expectCommaSeparator(); } } this.expect('}'); return this.finalize(node, new Node.ObjectExpression(properties)); }; // path_to_url#sec-template-literals Parser.prototype.parseTemplateHead = function () { assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); var node = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); }; Parser.prototype.parseTemplateElement = function () { if (this.lookahead.type !== 10 /* Template */) { this.throwUnexpectedToken(); } var node = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); }; Parser.prototype.parseTemplateLiteral = function () { var node = this.createNode(); var expressions = []; var quasis = []; var quasi = this.parseTemplateHead(); quasis.push(quasi); while (!quasi.tail) { expressions.push(this.parseExpression()); quasi = this.parseTemplateElement(); quasis.push(quasi); } return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); }; // path_to_url#sec-grouping-operator Parser.prototype.reinterpretExpressionAsPattern = function (expr) { switch (expr.type) { case syntax_1.Syntax.Identifier: case syntax_1.Syntax.MemberExpression: case syntax_1.Syntax.RestElement: case syntax_1.Syntax.AssignmentPattern: break; case syntax_1.Syntax.SpreadElement: expr.type = syntax_1.Syntax.RestElement; this.reinterpretExpressionAsPattern(expr.argument); break; case syntax_1.Syntax.ArrayExpression: expr.type = syntax_1.Syntax.ArrayPattern; for (var i = 0; i < expr.elements.length; i++) { if (expr.elements[i] !== null) { this.reinterpretExpressionAsPattern(expr.elements[i]); } } break; case syntax_1.Syntax.ObjectExpression: expr.type = syntax_1.Syntax.ObjectPattern; for (var i = 0; i < expr.properties.length; i++) { this.reinterpretExpressionAsPattern(expr.properties[i].value); } break; case syntax_1.Syntax.AssignmentExpression: expr.type = syntax_1.Syntax.AssignmentPattern; delete expr.operator; this.reinterpretExpressionAsPattern(expr.left); break; default: // Allow other node type for tolerant parsing. break; } }; Parser.prototype.parseGroupExpression = function () { var expr; this.expect('('); if (this.match(')')) { this.nextToken(); if (!this.match('=>')) { this.expect('=>'); } expr = { type: ArrowParameterPlaceHolder, params: [], async: false }; } else { var startToken = this.lookahead; var params = []; if (this.match('...')) { expr = this.parseRestElement(params); this.expect(')'); if (!this.match('=>')) { this.expect('=>'); } expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } else { var arrow = false; this.context.isBindingElement = true; expr = this.inheritCoverGrammar(this.parseAssignmentExpression); if (this.match(',')) { var expressions = []; this.context.isAssignmentTarget = false; expressions.push(expr); while (this.lookahead.type !== 2 /* EOF */) { if (!this.match(',')) { break; } this.nextToken(); if (this.match(')')) { this.nextToken(); for (var i = 0; i < expressions.length; i++) { this.reinterpretExpressionAsPattern(expressions[i]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else if (this.match('...')) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } expressions.push(this.parseRestElement(params)); this.expect(')'); if (!this.match('=>')) { this.expect('=>'); } this.context.isBindingElement = false; for (var i = 0; i < expressions.length; i++) { this.reinterpretExpressionAsPattern(expressions[i]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else { expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); } if (arrow) { break; } } if (!arrow) { expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } } if (!arrow) { this.expect(')'); if (this.match('=>')) { if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { arrow = true; expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } if (!arrow) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } if (expr.type === syntax_1.Syntax.SequenceExpression) { for (var i = 0; i < expr.expressions.length; i++) { this.reinterpretExpressionAsPattern(expr.expressions[i]); } } else { this.reinterpretExpressionAsPattern(expr); } var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); expr = { type: ArrowParameterPlaceHolder, params: parameters, async: false }; } } this.context.isBindingElement = false; } } } return expr; }; // path_to_url#sec-left-hand-side-expressions Parser.prototype.parseArguments = function () { this.expect('('); var args = []; if (!this.match(')')) { while (true) { var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression); args.push(expr); if (this.match(')')) { break; } this.expectCommaSeparator(); if (this.match(')')) { break; } } } this.expect(')'); return args; }; Parser.prototype.isIdentifierName = function (token) { return token.type === 3 /* Identifier */ || token.type === 4 /* Keyword */ || token.type === 1 /* BooleanLiteral */ || token.type === 5 /* NullLiteral */; }; Parser.prototype.parseIdentifierName = function () { var node = this.createNode(); var token = this.nextToken(); if (!this.isIdentifierName(token)) { this.throwUnexpectedToken(token); } return this.finalize(node, new Node.Identifier(token.value)); }; Parser.prototype.parseNewExpression = function () { var node = this.createNode(); var id = this.parseIdentifierName(); assert_1.assert(id.name === 'new', 'New expression must start with `new`'); var expr; if (this.match('.')) { this.nextToken(); if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { var property = this.parseIdentifierName(); expr = new Node.MetaProperty(id, property); } else { this.throwUnexpectedToken(this.lookahead); } } else { var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); var args = this.match('(') ? this.parseArguments() : []; expr = new Node.NewExpression(callee, args); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return this.finalize(node, expr); }; Parser.prototype.parseAsyncArgument = function () { var arg = this.parseAssignmentExpression(); this.context.firstCoverInitializedNameError = null; return arg; }; Parser.prototype.parseAsyncArguments = function () { this.expect('('); var args = []; if (!this.match(')')) { while (true) { var expr = this.match('...') ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument); args.push(expr); if (this.match(')')) { break; } this.expectCommaSeparator(); if (this.match(')')) { break; } } } this.expect(')'); return args; }; Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { var startToken = this.lookahead; var maybeAsync = this.matchContextualKeyword('async'); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var expr; if (this.matchKeyword('super') && this.context.inFunctionBody) { expr = this.createNode(); this.nextToken(); expr = this.finalize(expr, new Node.Super()); if (!this.match('(') && !this.match('.') && !this.match('[')) { this.throwUnexpectedToken(this.lookahead); } } else { expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); } while (true) { if (this.match('.')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('.'); var property = this.parseIdentifierName(); expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); } else if (this.match('(')) { var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); this.context.isBindingElement = false; this.context.isAssignmentTarget = false; var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); if (asyncArrow && this.match('=>')) { for (var i = 0; i < args.length; ++i) { this.reinterpretExpressionAsPattern(args[i]); } expr = { type: ArrowParameterPlaceHolder, params: args, async: true }; } } else if (this.match('[')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('['); var property = this.isolateCoverGrammar(this.parseExpression); this.expect(']'); expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); } else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } this.context.allowIn = previousAllowIn; return expr; }; Parser.prototype.parseSuper = function () { var node = this.createNode(); this.expectKeyword('super'); if (!this.match('[') && !this.match('.')) { this.throwUnexpectedToken(this.lookahead); } return this.finalize(node, new Node.Super()); }; Parser.prototype.parseLeftHandSideExpression = function () { assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); var node = this.startNode(this.lookahead); var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); while (true) { if (this.match('[')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('['); var property = this.isolateCoverGrammar(this.parseExpression); this.expect(']'); expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); } else if (this.match('.')) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect('.'); var property = this.parseIdentifierName(); expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); } else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } return expr; }; // path_to_url#sec-update-expressions Parser.prototype.parseUpdateExpression = function () { var expr; var startToken = this.lookahead; if (this.match('++') || this.match('--')) { var node = this.startNode(startToken); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPrefix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } var prefix = true; expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { if (this.match('++') || this.match('--')) { if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPostfix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var operator = this.nextToken().value; var prefix = false; expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); } } } return expr; }; // path_to_url#sec-unary-operators Parser.prototype.parseAwaitExpression = function () { var node = this.createNode(); this.nextToken(); var argument = this.parseUnaryExpression(); return this.finalize(node, new Node.AwaitExpression(argument)); }; Parser.prototype.parseUnaryExpression = function () { var expr; if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { var node = this.startNode(this.lookahead); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { this.tolerateError(messages_1.Messages.StrictDelete); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else if (this.context.await && this.matchContextualKeyword('await')) { expr = this.parseAwaitExpression(); } else { expr = this.parseUpdateExpression(); } return expr; }; Parser.prototype.parseExponentiationExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); } return expr; }; // path_to_url#sec-exp-operator // path_to_url#sec-multiplicative-operators // path_to_url#sec-additive-operators // path_to_url#sec-bitwise-shift-operators // path_to_url#sec-relational-operators // path_to_url#sec-equality-operators // path_to_url#sec-binary-bitwise-operators // path_to_url#sec-binary-logical-operators Parser.prototype.binaryPrecedence = function (token) { var op = token.value; var precedence; if (token.type === 7 /* Punctuator */) { precedence = this.operatorPrecedence[op] || 0; } else if (token.type === 4 /* Keyword */) { precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; } else { precedence = 0; } return precedence; }; Parser.prototype.parseBinaryExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); var token = this.lookahead; var prec = this.binaryPrecedence(token); if (prec > 0) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var markers = [startToken, this.lookahead]; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); var stack = [left, token.value, right]; var precedences = [prec]; while (true) { prec = this.binaryPrecedence(this.lookahead); if (prec <= 0) { break; } // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { right = stack.pop(); var operator = stack.pop(); precedences.pop(); left = stack.pop(); markers.pop(); var node = this.startNode(markers[markers.length - 1]); stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); } // Shift. stack.push(this.nextToken().value); precedences.push(prec); markers.push(this.lookahead); stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); } // Final reduce to clean-up the stack. var i = stack.length - 1; expr = stack[i]; var lastMarker = markers.pop(); while (i > 1) { var marker = markers.pop(); var lastLineStart = lastMarker && lastMarker.lineStart; var node = this.startNode(marker, lastLineStart); var operator = stack[i - 1]; expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); i -= 2; lastMarker = marker; } } return expr; }; // path_to_url#sec-conditional-operator Parser.prototype.parseConditionalExpression = function () { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseBinaryExpression); if (this.match('?')) { this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; this.expect(':'); var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return expr; }; // path_to_url#sec-assignment-operators Parser.prototype.checkPatternParam = function (options, param) { switch (param.type) { case syntax_1.Syntax.Identifier: this.validateParam(options, param, param.name); break; case syntax_1.Syntax.RestElement: this.checkPatternParam(options, param.argument); break; case syntax_1.Syntax.AssignmentPattern: this.checkPatternParam(options, param.left); break; case syntax_1.Syntax.ArrayPattern: for (var i = 0; i < param.elements.length; i++) { if (param.elements[i] !== null) { this.checkPatternParam(options, param.elements[i]); } } break; case syntax_1.Syntax.ObjectPattern: for (var i = 0; i < param.properties.length; i++) { this.checkPatternParam(options, param.properties[i].value); } break; default: break; } options.simple = options.simple && (param instanceof Node.Identifier); }; Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { var params = [expr]; var options; var asyncArrow = false; switch (expr.type) { case syntax_1.Syntax.Identifier: break; case ArrowParameterPlaceHolder: params = expr.params; asyncArrow = expr.async; break; default: return null; } options = { simple: true, paramSet: {} }; for (var i = 0; i < params.length; ++i) { var param = params[i]; if (param.type === syntax_1.Syntax.AssignmentPattern) { if (param.right.type === syntax_1.Syntax.YieldExpression) { if (param.right.argument) { this.throwUnexpectedToken(this.lookahead); } param.right.type = syntax_1.Syntax.Identifier; param.right.name = 'yield'; delete param.right.argument; delete param.right.delegate; } } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { this.throwUnexpectedToken(this.lookahead); } this.checkPatternParam(options, param); params[i] = param; } if (this.context.strict || !this.context.allowYield) { for (var i = 0; i < params.length; ++i) { var param = params[i]; if (param.type === syntax_1.Syntax.YieldExpression) { this.throwUnexpectedToken(this.lookahead); } } } if (options.message === messages_1.Messages.StrictParamDupe) { var token = this.context.strict ? options.stricted : options.firstRestricted; this.throwUnexpectedToken(token, options.message); } return { simple: options.simple, params: params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser.prototype.parseAssignmentExpression = function () { var expr; if (!this.context.allowYield && this.matchKeyword('yield')) { expr = this.parseYieldExpression(); } else { var startToken = this.lookahead; var token = startToken; expr = this.parseConditionalExpression(); if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { var arg = this.parsePrimaryExpression(); this.reinterpretExpressionAsPattern(arg); expr = { type: ArrowParameterPlaceHolder, params: [arg], async: true }; } } if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { // path_to_url#sec-arrow-function-definitions this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var isAsync = expr.async; var list = this.reinterpretAsCoverFormalsList(expr); if (list) { if (this.hasLineTerminator) { this.tolerateUnexpectedToken(this.lookahead); } this.context.firstCoverInitializedNameError = null; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = list.simple; var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = true; this.context.await = isAsync; var node = this.startNode(startToken); this.expect('=>'); var body = void 0; if (this.match('{')) { var previousAllowIn = this.context.allowIn; this.context.allowIn = true; body = this.parseFunctionSourceElements(); this.context.allowIn = previousAllowIn; } else { body = this.isolateCoverGrammar(this.parseAssignmentExpression); } var expression = body.type !== syntax_1.Syntax.BlockStatement; if (this.context.strict && list.firstRestricted) { this.throwUnexpectedToken(list.firstRestricted, list.message); } if (this.context.strict && list.stricted) { this.tolerateUnexpectedToken(list.stricted, list.message); } expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.allowYield = previousAllowYield; this.context.await = previousAwait; } } else { if (this.matchAssign()) { if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { var id = expr; if (this.scanner.isRestrictedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); } if (this.scanner.isStrictModeReservedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } } if (!this.match('=')) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { this.reinterpretExpressionAsPattern(expr); } token = this.nextToken(); var operator = token.value; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); this.context.firstCoverInitializedNameError = null; } } } return expr; }; // path_to_url#sec-comma-operator Parser.prototype.parseExpression = function () { var startToken = this.lookahead; var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); if (this.match(',')) { var expressions = []; expressions.push(expr); while (this.lookahead.type !== 2 /* EOF */) { if (!this.match(',')) { break; } this.nextToken(); expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } return expr; }; // path_to_url#sec-block Parser.prototype.parseStatementListItem = function () { var statement; this.context.isAssignmentTarget = true; this.context.isBindingElement = true; if (this.lookahead.type === 4 /* Keyword */) { switch (this.lookahead.value) { case 'export': if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); } statement = this.parseExportDeclaration(); break; case 'import': if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); } statement = this.parseImportDeclaration(); break; case 'const': statement = this.parseLexicalDeclaration({ inFor: false }); break; case 'function': statement = this.parseFunctionDeclaration(); break; case 'class': statement = this.parseClassDeclaration(); break; case 'let': statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); break; default: statement = this.parseStatement(); break; } } else { statement = this.parseStatement(); } return statement; }; Parser.prototype.parseBlock = function () { var node = this.createNode(); this.expect('{'); var block = []; while (true) { if (this.match('}')) { break; } block.push(this.parseStatementListItem()); } this.expect('}'); return this.finalize(node, new Node.BlockStatement(block)); }; // path_to_url#sec-let-and-const-declarations Parser.prototype.parseLexicalBinding = function (kind, options) { var node = this.createNode(); var params = []; var id = this.parsePattern(params, kind); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (kind === 'const') { if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { if (this.match('=')) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else { this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); } } } else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { this.expect('='); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } return this.finalize(node, new Node.VariableDeclarator(id, init)); }; Parser.prototype.parseBindingList = function (kind, options) { var list = [this.parseLexicalBinding(kind, options)]; while (this.match(',')) { this.nextToken(); list.push(this.parseLexicalBinding(kind, options)); } return list; }; Parser.prototype.isLexicalDeclaration = function () { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); return (next.type === 3 /* Identifier */) || (next.type === 7 /* Punctuator */ && next.value === '[') || (next.type === 7 /* Punctuator */ && next.value === '{') || (next.type === 4 /* Keyword */ && next.value === 'let') || (next.type === 4 /* Keyword */ && next.value === 'yield'); }; Parser.prototype.parseLexicalDeclaration = function (options) { var node = this.createNode(); var kind = this.nextToken().value; assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); var declarations = this.parseBindingList(kind, options); this.consumeSemicolon(); return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); }; // path_to_url#sec-destructuring-binding-patterns Parser.prototype.parseBindingRestElement = function (params, kind) { var node = this.createNode(); this.expect('...'); var arg = this.parsePattern(params, kind); return this.finalize(node, new Node.RestElement(arg)); }; Parser.prototype.parseArrayPattern = function (params, kind) { var node = this.createNode(); this.expect('['); var elements = []; while (!this.match(']')) { if (this.match(',')) { this.nextToken(); elements.push(null); } else { if (this.match('...')) { elements.push(this.parseBindingRestElement(params, kind)); break; } else { elements.push(this.parsePatternWithDefault(params, kind)); } if (!this.match(']')) { this.expect(','); } } } this.expect(']'); return this.finalize(node, new Node.ArrayPattern(elements)); }; Parser.prototype.parsePropertyPattern = function (params, kind) { var node = this.createNode(); var computed = false; var shorthand = false; var method = false; var key; var value; if (this.lookahead.type === 3 /* Identifier */) { var keyToken = this.lookahead; key = this.parseVariableIdentifier(); var init = this.finalize(node, new Node.Identifier(keyToken.value)); if (this.match('=')) { params.push(keyToken); shorthand = true; this.nextToken(); var expr = this.parseAssignmentExpression(); value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); } else if (!this.match(':')) { params.push(keyToken); shorthand = true; value = init; } else { this.expect(':'); value = this.parsePatternWithDefault(params, kind); } } else { computed = this.match('['); key = this.parseObjectPropertyKey(); this.expect(':'); value = this.parsePatternWithDefault(params, kind); } return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); }; Parser.prototype.parseObjectPattern = function (params, kind) { var node = this.createNode(); var properties = []; this.expect('{'); while (!this.match('}')) { properties.push(this.parsePropertyPattern(params, kind)); if (!this.match('}')) { this.expect(','); } } this.expect('}'); return this.finalize(node, new Node.ObjectPattern(properties)); }; Parser.prototype.parsePattern = function (params, kind) { var pattern; if (this.match('[')) { pattern = this.parseArrayPattern(params, kind); } else if (this.match('{')) { pattern = this.parseObjectPattern(params, kind); } else { if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); } params.push(this.lookahead); pattern = this.parseVariableIdentifier(kind); } return pattern; }; Parser.prototype.parsePatternWithDefault = function (params, kind) { var startToken = this.lookahead; var pattern = this.parsePattern(params, kind); if (this.match('=')) { this.nextToken(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowYield = previousAllowYield; pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); } return pattern; }; // path_to_url#sec-variable-statement Parser.prototype.parseVariableIdentifier = function (kind) { var node = this.createNode(); var token = this.nextToken(); if (token.type === 4 /* Keyword */ && token.value === 'yield') { if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else if (!this.context.allowYield) { this.throwUnexpectedToken(token); } } else if (token.type !== 3 /* Identifier */) { if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else { if (this.context.strict || token.value !== 'let' || kind !== 'var') { this.throwUnexpectedToken(token); } } } else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { this.tolerateUnexpectedToken(token); } return this.finalize(node, new Node.Identifier(token.value)); }; Parser.prototype.parseVariableDeclaration = function (options) { var node = this.createNode(); var params = []; var id = this.parsePattern(params, 'var'); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (this.match('=')) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { this.expect('='); } return this.finalize(node, new Node.VariableDeclarator(id, init)); }; Parser.prototype.parseVariableDeclarationList = function (options) { var opt = { inFor: options.inFor }; var list = []; list.push(this.parseVariableDeclaration(opt)); while (this.match(',')) { this.nextToken(); list.push(this.parseVariableDeclaration(opt)); } return list; }; Parser.prototype.parseVariableStatement = function () { var node = this.createNode(); this.expectKeyword('var'); var declarations = this.parseVariableDeclarationList({ inFor: false }); this.consumeSemicolon(); return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); }; // path_to_url#sec-empty-statement Parser.prototype.parseEmptyStatement = function () { var node = this.createNode(); this.expect(';'); return this.finalize(node, new Node.EmptyStatement()); }; // path_to_url#sec-expression-statement Parser.prototype.parseExpressionStatement = function () { var node = this.createNode(); var expr = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node, new Node.ExpressionStatement(expr)); }; // path_to_url#sec-if-statement Parser.prototype.parseIfClause = function () { if (this.context.strict && this.matchKeyword('function')) { this.tolerateError(messages_1.Messages.StrictFunction); } return this.parseStatement(); }; Parser.prototype.parseIfStatement = function () { var node = this.createNode(); var consequent; var alternate = null; this.expectKeyword('if'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); consequent = this.parseIfClause(); if (this.matchKeyword('else')) { this.nextToken(); alternate = this.parseIfClause(); } } return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); }; // path_to_url#sec-do-while-statement Parser.prototype.parseDoWhileStatement = function () { var node = this.createNode(); this.expectKeyword('do'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; var body = this.parseStatement(); this.context.inIteration = previousInIteration; this.expectKeyword('while'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); } else { this.expect(')'); if (this.match(';')) { this.nextToken(); } } return this.finalize(node, new Node.DoWhileStatement(body, test)); }; // path_to_url#sec-while-statement Parser.prototype.parseWhileStatement = function () { var node = this.createNode(); var body; this.expectKeyword('while'); this.expect('('); var test = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.parseStatement(); this.context.inIteration = previousInIteration; } return this.finalize(node, new Node.WhileStatement(test, body)); }; // path_to_url#sec-for-statement // path_to_url#sec-for-in-and-for-of-statements Parser.prototype.parseForStatement = function () { var init = null; var test = null; var update = null; var forIn = true; var left, right; var node = this.createNode(); this.expectKeyword('for'); this.expect('('); if (this.match(';')) { this.nextToken(); } else { if (this.matchKeyword('var')) { init = this.createNode(); this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseVariableDeclarationList({ inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && this.matchKeyword('in')) { var decl = declarations[0]; if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); } init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); this.expect(';'); } } else if (this.matchKeyword('const') || this.matchKeyword('let')) { init = this.createNode(); var kind = this.nextToken().value; if (!this.context.strict && this.lookahead.value === 'in') { init = this.finalize(init, new Node.Identifier(kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else { var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseBindingList(kind, { inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { this.consumeSemicolon(); init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); } } } else { var initStartToken = this.lookahead; var previousAllowIn = this.context.allowIn; this.context.allowIn = false; init = this.inheritCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; if (this.matchKeyword('in')) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForIn); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseExpression(); init = null; } else if (this.matchContextualKeyword('of')) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { if (this.match(',')) { var initSeq = [init]; while (this.match(',')) { this.nextToken(); initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); } this.expect(';'); } } } if (typeof left === 'undefined') { if (!this.match(';')) { test = this.parseExpression(); } this.expect(';'); if (!this.match(')')) { update = this.parseExpression(); } } var body; if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.isolateCoverGrammar(this.parseStatement); this.context.inIteration = previousInIteration; } return (typeof left === 'undefined') ? this.finalize(node, new Node.ForStatement(init, test, update, body)) : forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : this.finalize(node, new Node.ForOfStatement(left, right, body)); }; // path_to_url#sec-continue-statement Parser.prototype.parseContinueStatement = function () { var node = this.createNode(); this.expectKeyword('continue'); var label = null; if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); label = id; var key = '$' + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } } this.consumeSemicolon(); if (label === null && !this.context.inIteration) { this.throwError(messages_1.Messages.IllegalContinue); } return this.finalize(node, new Node.ContinueStatement(label)); }; // path_to_url#sec-break-statement Parser.prototype.parseBreakStatement = function () { var node = this.createNode(); this.expectKeyword('break'); var label = null; if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); var key = '$' + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } label = id; } this.consumeSemicolon(); if (label === null && !this.context.inIteration && !this.context.inSwitch) { this.throwError(messages_1.Messages.IllegalBreak); } return this.finalize(node, new Node.BreakStatement(label)); }; // path_to_url#sec-return-statement Parser.prototype.parseReturnStatement = function () { if (!this.context.inFunctionBody) { this.tolerateError(messages_1.Messages.IllegalReturn); } var node = this.createNode(); this.expectKeyword('return'); var hasArgument = (!this.match(';') && !this.match('}') && !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) || this.lookahead.type === 8 /* StringLiteral */ || this.lookahead.type === 10 /* Template */; var argument = hasArgument ? this.parseExpression() : null; this.consumeSemicolon(); return this.finalize(node, new Node.ReturnStatement(argument)); }; // path_to_url#sec-with-statement Parser.prototype.parseWithStatement = function () { if (this.context.strict) { this.tolerateError(messages_1.Messages.StrictModeWith); } var node = this.createNode(); var body; this.expectKeyword('with'); this.expect('('); var object = this.parseExpression(); if (!this.match(')') && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(')'); body = this.parseStatement(); } return this.finalize(node, new Node.WithStatement(object, body)); }; // path_to_url#sec-switch-statement Parser.prototype.parseSwitchCase = function () { var node = this.createNode(); var test; if (this.matchKeyword('default')) { this.nextToken(); test = null; } else { this.expectKeyword('case'); test = this.parseExpression(); } this.expect(':'); var consequent = []; while (true) { if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { break; } consequent.push(this.parseStatementListItem()); } return this.finalize(node, new Node.SwitchCase(test, consequent)); }; Parser.prototype.parseSwitchStatement = function () { var node = this.createNode(); this.expectKeyword('switch'); this.expect('('); var discriminant = this.parseExpression(); this.expect(')'); var previousInSwitch = this.context.inSwitch; this.context.inSwitch = true; var cases = []; var defaultFound = false; this.expect('{'); while (true) { if (this.match('}')) { break; } var clause = this.parseSwitchCase(); if (clause.test === null) { if (defaultFound) { this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } this.expect('}'); this.context.inSwitch = previousInSwitch; return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); }; // path_to_url#sec-labelled-statements Parser.prototype.parseLabelledStatement = function () { var node = this.createNode(); var expr = this.parseExpression(); var statement; if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { this.nextToken(); var id = expr; var key = '$' + id.name; if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); } this.context.labelSet[key] = true; var body = void 0; if (this.matchKeyword('class')) { this.tolerateUnexpectedToken(this.lookahead); body = this.parseClassDeclaration(); } else if (this.matchKeyword('function')) { var token = this.lookahead; var declaration = this.parseFunctionDeclaration(); if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); } else if (declaration.generator) { this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); } body = declaration; } else { body = this.parseStatement(); } delete this.context.labelSet[key]; statement = new Node.LabeledStatement(id, body); } else { this.consumeSemicolon(); statement = new Node.ExpressionStatement(expr); } return this.finalize(node, statement); }; // path_to_url#sec-throw-statement Parser.prototype.parseThrowStatement = function () { var node = this.createNode(); this.expectKeyword('throw'); if (this.hasLineTerminator) { this.throwError(messages_1.Messages.NewlineAfterThrow); } var argument = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node, new Node.ThrowStatement(argument)); }; // path_to_url#sec-try-statement Parser.prototype.parseCatchClause = function () { var node = this.createNode(); this.expectKeyword('catch'); this.expect('('); if (this.match(')')) { this.throwUnexpectedToken(this.lookahead); } var params = []; var param = this.parsePattern(params); var paramMap = {}; for (var i = 0; i < params.length; i++) { var key = '$' + params[i].value; if (Object.prototype.hasOwnProperty.call(paramMap, key)) { this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); } paramMap[key] = true; } if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(param.name)) { this.tolerateError(messages_1.Messages.StrictCatchVariable); } } this.expect(')'); var body = this.parseBlock(); return this.finalize(node, new Node.CatchClause(param, body)); }; Parser.prototype.parseFinallyClause = function () { this.expectKeyword('finally'); return this.parseBlock(); }; Parser.prototype.parseTryStatement = function () { var node = this.createNode(); this.expectKeyword('try'); var block = this.parseBlock(); var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; if (!handler && !finalizer) { this.throwError(messages_1.Messages.NoCatchOrFinally); } return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); }; // path_to_url#sec-debugger-statement Parser.prototype.parseDebuggerStatement = function () { var node = this.createNode(); this.expectKeyword('debugger'); this.consumeSemicolon(); return this.finalize(node, new Node.DebuggerStatement()); }; // path_to_url#sec-ecmascript-language-statements-and-declarations Parser.prototype.parseStatement = function () { var statement; switch (this.lookahead.type) { case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 6 /* NumericLiteral */: case 8 /* StringLiteral */: case 10 /* Template */: case 9 /* RegularExpression */: statement = this.parseExpressionStatement(); break; case 7 /* Punctuator */: var value = this.lookahead.value; if (value === '{') { statement = this.parseBlock(); } else if (value === '(') { statement = this.parseExpressionStatement(); } else if (value === ';') { statement = this.parseEmptyStatement(); } else { statement = this.parseExpressionStatement(); } break; case 3 /* Identifier */: statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); break; case 4 /* Keyword */: switch (this.lookahead.value) { case 'break': statement = this.parseBreakStatement(); break; case 'continue': statement = this.parseContinueStatement(); break; case 'debugger': statement = this.parseDebuggerStatement(); break; case 'do': statement = this.parseDoWhileStatement(); break; case 'for': statement = this.parseForStatement(); break; case 'function': statement = this.parseFunctionDeclaration(); break; case 'if': statement = this.parseIfStatement(); break; case 'return': statement = this.parseReturnStatement(); break; case 'switch': statement = this.parseSwitchStatement(); break; case 'throw': statement = this.parseThrowStatement(); break; case 'try': statement = this.parseTryStatement(); break; case 'var': statement = this.parseVariableStatement(); break; case 'while': statement = this.parseWhileStatement(); break; case 'with': statement = this.parseWithStatement(); break; default: statement = this.parseExpressionStatement(); break; } break; default: statement = this.throwUnexpectedToken(this.lookahead); } return statement; }; // path_to_url#sec-function-definitions Parser.prototype.parseFunctionSourceElements = function () { var node = this.createNode(); this.expect('{'); var body = this.parseDirectivePrologues(); var previousLabelSet = this.context.labelSet; var previousInIteration = this.context.inIteration; var previousInSwitch = this.context.inSwitch; var previousInFunctionBody = this.context.inFunctionBody; this.context.labelSet = {}; this.context.inIteration = false; this.context.inSwitch = false; this.context.inFunctionBody = true; while (this.lookahead.type !== 2 /* EOF */) { if (this.match('}')) { break; } body.push(this.parseStatementListItem()); } this.expect('}'); this.context.labelSet = previousLabelSet; this.context.inIteration = previousInIteration; this.context.inSwitch = previousInSwitch; this.context.inFunctionBody = previousInFunctionBody; return this.finalize(node, new Node.BlockStatement(body)); }; Parser.prototype.validateParam = function (options, param, name) { var key = '$' + name; if (this.context.strict) { if (this.scanner.isRestrictedWord(name)) { options.stricted = param; options.message = messages_1.Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (this.scanner.isRestrictedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictParamName; } else if (this.scanner.isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } /* istanbul ignore next */ if (typeof Object.defineProperty === 'function') { Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); } else { options.paramSet[key] = true; } }; Parser.prototype.parseRestElement = function (params) { var node = this.createNode(); this.expect('...'); var arg = this.parsePattern(params); if (this.match('=')) { this.throwError(messages_1.Messages.DefaultRestParameter); } if (!this.match(')')) { this.throwError(messages_1.Messages.ParameterAfterRestParameter); } return this.finalize(node, new Node.RestElement(arg)); }; Parser.prototype.parseFormalParameter = function (options) { var params = []; var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); for (var i = 0; i < params.length; i++) { this.validateParam(options, params[i], params[i].value); } options.simple = options.simple && (param instanceof Node.Identifier); options.params.push(param); }; Parser.prototype.parseFormalParameters = function (firstRestricted) { var options; options = { simple: true, params: [], firstRestricted: firstRestricted }; this.expect('('); if (!this.match(')')) { options.paramSet = {}; while (this.lookahead.type !== 2 /* EOF */) { this.parseFormalParameter(options); if (this.match(')')) { break; } this.expect(','); if (this.match(')')) { break; } } } this.expect(')'); return { simple: options.simple, params: options.params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser.prototype.matchAsyncFunction = function () { var match = this.matchContextualKeyword('async'); if (match) { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); } return match; }; Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { var node = this.createNode(); var isAsync = this.matchContextualKeyword('async'); if (isAsync) { this.nextToken(); } this.expectKeyword('function'); var isGenerator = isAsync ? false : this.match('*'); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted = null; if (!identifierIsOptional || !this.match('(')) { var token = this.lookahead; id = this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); }; Parser.prototype.parseFunctionExpression = function () { var node = this.createNode(); var isAsync = this.matchContextualKeyword('async'); if (isAsync) { this.nextToken(); } this.expectKeyword('function'); var isGenerator = isAsync ? false : this.match('*'); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted; var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync; this.context.allowYield = !isGenerator; if (!this.match('(')) { var token = this.lookahead; id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); }; // path_to_url#sec-directive-prologues-and-the-use-strict-directive Parser.prototype.parseDirective = function () { var token = this.lookahead; var node = this.createNode(); var expr = this.parseExpression(); var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; this.consumeSemicolon(); return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); }; Parser.prototype.parseDirectivePrologues = function () { var firstRestricted = null; var body = []; while (true) { var token = this.lookahead; if (token.type !== 8 /* StringLiteral */) { break; } var statement = this.parseDirective(); body.push(statement); var directive = statement.directive; if (typeof directive !== 'string') { break; } if (directive === 'use strict') { this.context.strict = true; if (firstRestricted) { this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); } if (!this.context.allowStrictDirective) { this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } return body; }; // path_to_url#sec-method-definitions Parser.prototype.qualifiedPropertyName = function (token) { switch (token.type) { case 3 /* Identifier */: case 8 /* StringLiteral */: case 1 /* BooleanLiteral */: case 5 /* NullLiteral */: case 6 /* NumericLiteral */: case 4 /* Keyword */: return true; case 7 /* Punctuator */: return token.value === '['; default: break; } return false; }; Parser.prototype.parseGetterMethod = function () { var node = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length > 0) { this.tolerateError(messages_1.Messages.BadGetterArity); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser.prototype.parseSetterMethod = function () { var node = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length !== 1) { this.tolerateError(messages_1.Messages.BadSetterArity); } else if (formalParameters.params[0] instanceof Node.RestElement) { this.tolerateError(messages_1.Messages.BadSetterRestParameter); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser.prototype.parseGeneratorMethod = function () { var node = this.createNode(); var isGenerator = true; var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); this.context.allowYield = false; var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; // path_to_url#sec-generator-function-definitions Parser.prototype.isStartOfExpression = function () { var start = true; var value = this.lookahead.value; switch (this.lookahead.type) { case 7 /* Punctuator */: start = (value === '[') || (value === '(') || (value === '{') || (value === '+') || (value === '-') || (value === '!') || (value === '~') || (value === '++') || (value === '--') || (value === '/') || (value === '/='); // regular expression literal break; case 4 /* Keyword */: start = (value === 'class') || (value === 'delete') || (value === 'function') || (value === 'let') || (value === 'new') || (value === 'super') || (value === 'this') || (value === 'typeof') || (value === 'void') || (value === 'yield'); break; default: break; } return start; }; Parser.prototype.parseYieldExpression = function () { var node = this.createNode(); this.expectKeyword('yield'); var argument = null; var delegate = false; if (!this.hasLineTerminator) { var previousAllowYield = this.context.allowYield; this.context.allowYield = false; delegate = this.match('*'); if (delegate) { this.nextToken(); argument = this.parseAssignmentExpression(); } else if (this.isStartOfExpression()) { argument = this.parseAssignmentExpression(); } this.context.allowYield = previousAllowYield; } return this.finalize(node, new Node.YieldExpression(argument, delegate)); }; // path_to_url#sec-class-definitions Parser.prototype.parseClassElement = function (hasConstructor) { var token = this.lookahead; var node = this.createNode(); var kind = ''; var key = null; var value = null; var computed = false; var method = false; var isStatic = false; var isAsync = false; if (this.match('*')) { this.nextToken(); } else { computed = this.match('['); key = this.parseObjectPropertyKey(); var id = key; if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { token = this.lookahead; isStatic = true; computed = this.match('['); if (this.match('*')) { this.nextToken(); } else { key = this.parseObjectPropertyKey(); } } if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { var punctuator = this.lookahead.value; if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { isAsync = true; token = this.lookahead; key = this.parseObjectPropertyKey(); if (token.type === 3 /* Identifier */ && token.value === 'constructor') { this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); } } } } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3 /* Identifier */) { if (token.value === 'get' && lookaheadPropertyKey) { kind = 'get'; computed = this.match('['); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.value === 'set' && lookaheadPropertyKey) { kind = 'set'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } } else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { kind = 'init'; computed = this.match('['); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } if (!kind && key && this.match('(')) { kind = 'init'; value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } if (!kind) { this.throwUnexpectedToken(this.lookahead); } if (kind === 'init') { kind = 'method'; } if (!computed) { if (isStatic && this.isPropertyKey(key, 'prototype')) { this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); } if (!isStatic && this.isPropertyKey(key, 'constructor')) { if (kind !== 'method' || !method || (value && value.generator)) { this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); } if (hasConstructor.value) { this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); } else { hasConstructor.value = true; } kind = 'constructor'; } } return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); }; Parser.prototype.parseClassElementList = function () { var body = []; var hasConstructor = { value: false }; this.expect('{'); while (!this.match('}')) { if (this.match(';')) { this.nextToken(); } else { body.push(this.parseClassElement(hasConstructor)); } } this.expect('}'); return body; }; Parser.prototype.parseClassBody = function () { var node = this.createNode(); var elementList = this.parseClassElementList(); return this.finalize(node, new Node.ClassBody(elementList)); }; Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { var node = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword('class'); var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); var superClass = null; if (this.matchKeyword('extends')) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); }; Parser.prototype.parseClassExpression = function () { var node = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword('class'); var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; var superClass = null; if (this.matchKeyword('extends')) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); }; // path_to_url#sec-scripts // path_to_url#sec-modules Parser.prototype.parseModule = function () { this.context.strict = true; this.context.isModule = true; this.scanner.isModule = true; var node = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2 /* EOF */) { body.push(this.parseStatementListItem()); } return this.finalize(node, new Node.Module(body)); }; Parser.prototype.parseScript = function () { var node = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2 /* EOF */) { body.push(this.parseStatementListItem()); } return this.finalize(node, new Node.Script(body)); }; // path_to_url#sec-imports Parser.prototype.parseModuleSpecifier = function () { var node = this.createNode(); if (this.lookahead.type !== 8 /* StringLiteral */) { this.throwError(messages_1.Messages.InvalidModuleSpecifier); } var token = this.nextToken(); var raw = this.getTokenRaw(token); return this.finalize(node, new Node.Literal(token.value, raw)); }; // import {<foo as bar>} ...; Parser.prototype.parseImportSpecifier = function () { var node = this.createNode(); var imported; var local; if (this.lookahead.type === 3 /* Identifier */) { imported = this.parseVariableIdentifier(); local = imported; if (this.matchContextualKeyword('as')) { this.nextToken(); local = this.parseVariableIdentifier(); } } else { imported = this.parseIdentifierName(); local = imported; if (this.matchContextualKeyword('as')) { this.nextToken(); local = this.parseVariableIdentifier(); } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node, new Node.ImportSpecifier(local, imported)); }; // {foo, bar as bas} Parser.prototype.parseNamedImports = function () { this.expect('{'); var specifiers = []; while (!this.match('}')) { specifiers.push(this.parseImportSpecifier()); if (!this.match('}')) { this.expect(','); } } this.expect('}'); return specifiers; }; // import <foo> ...; Parser.prototype.parseImportDefaultSpecifier = function () { var node = this.createNode(); var local = this.parseIdentifierName(); return this.finalize(node, new Node.ImportDefaultSpecifier(local)); }; // import <* as foo> ...; Parser.prototype.parseImportNamespaceSpecifier = function () { var node = this.createNode(); this.expect('*'); if (!this.matchContextualKeyword('as')) { this.throwError(messages_1.Messages.NoAsAfterImportNamespace); } this.nextToken(); var local = this.parseIdentifierName(); return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); }; Parser.prototype.parseImportDeclaration = function () { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalImportDeclaration); } var node = this.createNode(); this.expectKeyword('import'); var src; var specifiers = []; if (this.lookahead.type === 8 /* StringLiteral */) { // import 'foo'; src = this.parseModuleSpecifier(); } else { if (this.match('{')) { // import {bar} specifiers = specifiers.concat(this.parseNamedImports()); } else if (this.match('*')) { // import * as foo specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { // import foo specifiers.push(this.parseImportDefaultSpecifier()); if (this.match(',')) { this.nextToken(); if (this.match('*')) { // import foo, * as foo specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.match('{')) { // import foo, {bar} specifiers = specifiers.concat(this.parseNamedImports()); } else { this.throwUnexpectedToken(this.lookahead); } } } else { this.throwUnexpectedToken(this.nextToken()); } if (!this.matchContextualKeyword('from')) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); src = this.parseModuleSpecifier(); } this.consumeSemicolon(); return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); }; // path_to_url#sec-exports Parser.prototype.parseExportSpecifier = function () { var node = this.createNode(); var local = this.parseIdentifierName(); var exported = local; if (this.matchContextualKeyword('as')) { this.nextToken(); exported = this.parseIdentifierName(); } return this.finalize(node, new Node.ExportSpecifier(local, exported)); }; Parser.prototype.parseExportDeclaration = function () { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalExportDeclaration); } var node = this.createNode(); this.expectKeyword('export'); var exportDeclaration; if (this.matchKeyword('default')) { // export default ... this.nextToken(); if (this.matchKeyword('function')) { // export default function foo () {} // export default function () {} var declaration = this.parseFunctionDeclaration(true); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchKeyword('class')) { // export default class foo {} var declaration = this.parseClassDeclaration(true); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchContextualKeyword('async')) { // export default async function f () {} // export default async function () {} // export default async x => x var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } else { if (this.matchContextualKeyword('from')) { this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); } // export default {}; // export default []; // export default (1 + 2); var declaration = this.match('{') ? this.parseObjectInitializer() : this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); this.consumeSemicolon(); exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); } } else if (this.match('*')) { // export * from 'foo'; this.nextToken(); if (!this.matchContextualKeyword('from')) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); var src = this.parseModuleSpecifier(); this.consumeSemicolon(); exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); } else if (this.lookahead.type === 4 /* Keyword */) { // export var f = 1; var declaration = void 0; switch (this.lookahead.value) { case 'let': case 'const': declaration = this.parseLexicalDeclaration({ inFor: false }); break; case 'var': case 'class': case 'function': declaration = this.parseStatementListItem(); break; default: this.throwUnexpectedToken(this.lookahead); } exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); } else if (this.matchAsyncFunction()) { var declaration = this.parseFunctionDeclaration(); exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); } else { var specifiers = []; var source = null; var isExportFromIdentifier = false; this.expect('{'); while (!this.match('}')) { isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); specifiers.push(this.parseExportSpecifier()); if (!this.match('}')) { this.expect(','); } } this.expect('}'); if (this.matchContextualKeyword('from')) { // export {default} from 'foo'; // export {foo} from 'foo'; this.nextToken(); source = this.parseModuleSpecifier(); this.consumeSemicolon(); } else if (isExportFromIdentifier) { // export {default}; // missing fromClause var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } else { // export {foo}; this.consumeSemicolon(); } exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); } return exportDeclaration; }; return Parser; }()); exports.Parser = Parser; /***/ }, /* 9 */ /***/ function(module, exports) { "use strict"; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. Object.defineProperty(exports, "__esModule", { value: true }); function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } exports.assert = assert; /***/ }, /* 10 */ /***/ function(module, exports) { "use strict"; /* tslint:disable:max-classes-per-file */ Object.defineProperty(exports, "__esModule", { value: true }); var ErrorHandler = (function () { function ErrorHandler() { this.errors = []; this.tolerant = false; } ErrorHandler.prototype.recordError = function (error) { this.errors.push(error); }; ErrorHandler.prototype.tolerate = function (error) { if (this.tolerant) { this.recordError(error); } else { throw error; } }; ErrorHandler.prototype.constructError = function (msg, column) { var error = new Error(msg); try { throw error; } catch (base) { /* istanbul ignore else */ if (Object.create && Object.defineProperty) { error = Object.create(base); Object.defineProperty(error, 'column', { value: column }); } } /* istanbul ignore next */ return error; }; ErrorHandler.prototype.createError = function (index, line, col, description) { var msg = 'Line ' + line + ': ' + description; var error = this.constructError(msg, col); error.index = index; error.lineNumber = line; error.description = description; return error; }; ErrorHandler.prototype.throwError = function (index, line, col, description) { throw this.createError(index, line, col, description); }; ErrorHandler.prototype.tolerateError = function (index, line, col, description) { var error = this.createError(index, line, col, description); if (this.tolerant) { this.recordError(error); } else { throw error; } }; return ErrorHandler; }()); exports.ErrorHandler = ErrorHandler; /***/ }, /* 11 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Error messages should be identical to V8. exports.Messages = { BadGetterArity: 'Getter must not have any formal parameters', BadSetterArity: 'Setter must have exactly one formal parameter', BadSetterRestParameter: 'Setter function argument must not be a rest parameter', ConstructorIsAsync: 'Class constructor may not be an async method', ConstructorSpecialMethod: 'Class constructor may not be an accessor', DeclarationMissingInitializer: 'Missing initializer in %0 declaration', DefaultRestParameter: 'Unexpected token =', DuplicateBinding: 'Duplicate binding %0', DuplicateConstructor: 'A class may only have one constructor', DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', IllegalBreak: 'Illegal break statement', IllegalContinue: 'Illegal continue statement', IllegalExportDeclaration: 'Unexpected token', IllegalImportDeclaration: 'Unexpected token', IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', IllegalReturn: 'Illegal return statement', InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInForIn: 'Invalid left-hand side in for-in', InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', InvalidModuleSpecifier: 'Unexpected token', InvalidRegExp: 'Invalid regular expression', LetInLexicalBinding: 'let is disallowed as a lexically bound name', MissingFromClause: 'Unexpected token', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NewlineAfterThrow: 'Illegal newline after throw', NoAsAfterImportNamespace: 'Unexpected token', NoCatchOrFinally: 'Missing catch or finally after try', ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', Redeclaration: '%0 \'%1\' has already been declared', StaticPrototype: 'Classes may not have static property named prototype', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictModeWith: 'Strict mode code may not include a with statement', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', UnexpectedEOS: 'Unexpected end of input', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedNumber: 'Unexpected number', UnexpectedReserved: 'Unexpected reserved word', UnexpectedString: 'Unexpected string', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedToken: 'Unexpected token %0', UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', UnknownLabel: 'Undefined label \'%0\'', UnterminatedRegExp: 'Invalid regular expression: missing /' }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var assert_1 = __webpack_require__(9); var character_1 = __webpack_require__(4); var messages_1 = __webpack_require__(11); function hexValue(ch) { return '0123456789abcdef'.indexOf(ch.toLowerCase()); } function octalValue(ch) { return '01234567'.indexOf(ch); } var Scanner = (function () { function Scanner(code, handler) { this.source = code; this.errorHandler = handler; this.trackComment = false; this.isModule = false; this.length = code.length; this.index = 0; this.lineNumber = (code.length > 0) ? 1 : 0; this.lineStart = 0; this.curlyStack = []; } Scanner.prototype.saveState = function () { return { index: this.index, lineNumber: this.lineNumber, lineStart: this.lineStart }; }; Scanner.prototype.restoreState = function (state) { this.index = state.index; this.lineNumber = state.lineNumber; this.lineStart = state.lineStart; }; Scanner.prototype.eof = function () { return this.index >= this.length; }; Scanner.prototype.throwUnexpectedToken = function (message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; Scanner.prototype.tolerateUnexpectedToken = function (message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; // path_to_url#sec-comments Scanner.prototype.skipSingleLineComment = function (offset) { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - offset; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - offset }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); ++this.index; if (character_1.Character.isLineTerminator(ch)) { if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart - 1 }; var entry = { multiLine: false, slice: [start + offset, this.index - 1], range: [start, this.index - 1], loc: loc }; comments.push(entry); } if (ch === 13 && this.source.charCodeAt(this.index) === 10) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; return comments; } } if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: false, slice: [start + offset, this.index], range: [start, this.index], loc: loc }; comments.push(entry); } return comments; }; Scanner.prototype.skipMultiLineComment = function () { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - 2; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - 2 }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isLineTerminator(ch)) { if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { ++this.index; } ++this.lineNumber; ++this.index; this.lineStart = this.index; } else if (ch === 0x2A) { // Block comment ends with '*/'. if (this.source.charCodeAt(this.index + 1) === 0x2F) { this.index += 2; if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index - 2], range: [start, this.index], loc: loc }; comments.push(entry); } return comments; } ++this.index; } else { ++this.index; } } // Ran off the end of the file - the whole thing is a comment if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index], range: [start, this.index], loc: loc }; comments.push(entry); } this.tolerateUnexpectedToken(); return comments; }; Scanner.prototype.scanComments = function () { var comments; if (this.trackComment) { comments = []; } var start = (this.index === 0); while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isWhiteSpace(ch)) { ++this.index; } else if (character_1.Character.isLineTerminator(ch)) { ++this.index; if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; start = true; } else if (ch === 0x2F) { ch = this.source.charCodeAt(this.index + 1); if (ch === 0x2F) { this.index += 2; var comment = this.skipSingleLineComment(2); if (this.trackComment) { comments = comments.concat(comment); } start = true; } else if (ch === 0x2A) { this.index += 2; var comment = this.skipMultiLineComment(); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (start && ch === 0x2D) { // U+003E is '>' if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { // '-->' is a single-line comment this.index += 3; var comment = this.skipSingleLineComment(3); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (ch === 0x3C && !this.isModule) { if (this.source.slice(this.index + 1, this.index + 4) === '!--') { this.index += 4; // `<!--` var comment = this.skipSingleLineComment(4); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else { break; } } return comments; }; // path_to_url#sec-future-reserved-words Scanner.prototype.isFutureReservedWord = function (id) { switch (id) { case 'enum': case 'export': case 'import': case 'super': return true; default: return false; } }; Scanner.prototype.isStrictModeReservedWord = function (id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } }; Scanner.prototype.isRestrictedWord = function (id) { return id === 'eval' || id === 'arguments'; }; // path_to_url#sec-keywords Scanner.prototype.isKeyword = function (id) { switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } }; Scanner.prototype.codePointAt = function (i) { var cp = this.source.charCodeAt(i); if (cp >= 0xD800 && cp <= 0xDBFF) { var second = this.source.charCodeAt(i + 1); if (second >= 0xDC00 && second <= 0xDFFF) { var first = cp; cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return cp; }; Scanner.prototype.scanHexEscape = function (prefix) { var len = (prefix === 'u') ? 4 : 2; var code = 0; for (var i = 0; i < len; ++i) { if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { code = code * 16 + hexValue(this.source[this.index++]); } else { return null; } } return String.fromCharCode(code); }; Scanner.prototype.scanUnicodeCodePointEscape = function () { var ch = this.source[this.index]; var code = 0; // At least, one hex digit is required. if (ch === '}') { this.throwUnexpectedToken(); } while (!this.eof()) { ch = this.source[this.index++]; if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) { break; } code = code * 16 + hexValue(ch); } if (code > 0x10FFFF || ch !== '}') { this.throwUnexpectedToken(); } return character_1.Character.fromCodePoint(code); }; Scanner.prototype.getIdentifier = function () { var start = this.index++; while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (ch === 0x5C) { // Blackslash (U+005C) marks Unicode escape sequence. this.index = start; return this.getComplexIdentifier(); } else if (ch >= 0xD800 && ch < 0xDFFF) { // Need to handle surrogate pairs. this.index = start; return this.getComplexIdentifier(); } if (character_1.Character.isIdentifierPart(ch)) { ++this.index; } else { break; } } return this.source.slice(start, this.index); }; Scanner.prototype.getComplexIdentifier = function () { var cp = this.codePointAt(this.index); var id = character_1.Character.fromCodePoint(cp); this.index += id.length; // '\u' (U+005C, U+0075) denotes an escaped character. var ch; if (cp === 0x5C) { if (this.source.charCodeAt(this.index) !== 0x75) { this.throwUnexpectedToken(); } ++this.index; if (this.source[this.index] === '{') { ++this.index; ch = this.scanUnicodeCodePointEscape(); } else { ch = this.scanHexEscape('u'); if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) { this.throwUnexpectedToken(); } } id = ch; } while (!this.eof()) { cp = this.codePointAt(this.index); if (!character_1.Character.isIdentifierPart(cp)) { break; } ch = character_1.Character.fromCodePoint(cp); id += ch; this.index += ch.length; // '\u' (U+005C, U+0075) denotes an escaped character. if (cp === 0x5C) { id = id.substr(0, id.length - 1); if (this.source.charCodeAt(this.index) !== 0x75) { this.throwUnexpectedToken(); } ++this.index; if (this.source[this.index] === '{') { ++this.index; ch = this.scanUnicodeCodePointEscape(); } else { ch = this.scanHexEscape('u'); if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { this.throwUnexpectedToken(); } } id += ch; } } return id; }; Scanner.prototype.octalToDecimal = function (ch) { // \0 is not octal escape sequence var octal = (ch !== '0'); var code = octalValue(ch); if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { octal = true; code = code * 8 + octalValue(this.source[this.index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { code = code * 8 + octalValue(this.source[this.index++]); } } return { code: code, octal: octal }; }; // path_to_url#sec-names-and-keywords Scanner.prototype.scanIdentifier = function () { var type; var start = this.index; // Backslash (U+005C) starts an escaped character. var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = 3 /* Identifier */; } else if (this.isKeyword(id)) { type = 4 /* Keyword */; } else if (id === 'null') { type = 5 /* NullLiteral */; } else if (id === 'true' || id === 'false') { type = 1 /* BooleanLiteral */; } else { type = 3 /* Identifier */; } if (type !== 3 /* Identifier */ && (start + id.length !== this.index)) { var restore = this.index; this.index = start; this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord); this.index = restore; } return { type: type, value: id, lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; // path_to_url#sec-punctuators Scanner.prototype.scanPunctuator = function () { var start = this.index; // Check for most common single-character punctuators. var str = this.source[this.index]; switch (str) { case '(': case '{': if (str === '{') { this.curlyStack.push('{'); } ++this.index; break; case '.': ++this.index; if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') { // Spread operator: ... this.index += 2; str = '...'; } break; case '}': ++this.index; this.curlyStack.pop(); break; case ')': case ';': case ',': case '[': case ']': case ':': case '?': case '~': ++this.index; break; default: // 4-character punctuator. str = this.source.substr(this.index, 4); if (str === '>>>=') { this.index += 4; } else { // 3-character punctuators. str = str.substr(0, 3); if (str === '===' || str === '!==' || str === '>>>' || str === '<<=' || str === '>>=' || str === '**=') { this.index += 3; } else { // 2-character punctuators. str = str.substr(0, 2); if (str === '&&' || str === '||' || str === '==' || str === '!=' || str === '+=' || str === '-=' || str === '*=' || str === '/=' || str === '++' || str === '--' || str === '<<' || str === '>>' || str === '&=' || str === '|=' || str === '^=' || str === '%=' || str === '<=' || str === '>=' || str === '=>' || str === '**') { this.index += 2; } else { // 1-character punctuators. str = this.source[this.index]; if ('<>=!+-*%&|^/'.indexOf(str) >= 0) { ++this.index; } } } } } if (this.index === start) { this.throwUnexpectedToken(); } return { type: 7 /* Punctuator */, value: str, lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; // path_to_url#sec-literals-numeric-literals Scanner.prototype.scanHexLiteral = function (start) { var num = ''; while (!this.eof()) { if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { break; } num += this.source[this.index++]; } if (num.length === 0) { this.throwUnexpectedToken(); } if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { this.throwUnexpectedToken(); } return { type: 6 /* NumericLiteral */, value: parseInt('0x' + num, 16), lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; Scanner.prototype.scanBinaryLiteral = function (start) { var num = ''; var ch; while (!this.eof()) { ch = this.source[this.index]; if (ch !== '0' && ch !== '1') { break; } num += this.source[this.index++]; } if (num.length === 0) { // only 0b or 0B this.throwUnexpectedToken(); } if (!this.eof()) { ch = this.source.charCodeAt(this.index); /* istanbul ignore else */ if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) { this.throwUnexpectedToken(); } } return { type: 6 /* NumericLiteral */, value: parseInt(num, 2), lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; Scanner.prototype.scanOctalLiteral = function (prefix, start) { var num = ''; var octal = false; if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) { octal = true; num = '0' + this.source[this.index++]; } else { ++this.index; } while (!this.eof()) { if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { break; } num += this.source[this.index++]; } if (!octal && num.length === 0) { // only 0o or 0O this.throwUnexpectedToken(); } if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { this.throwUnexpectedToken(); } return { type: 6 /* NumericLiteral */, value: parseInt(num, 8), octal: octal, lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; Scanner.prototype.isImplicitOctalLiteral = function () { // Implicit octal, unless there is a non-octal digit. // (Annex B.1.1 on Numeric Literals) for (var i = this.index + 1; i < this.length; ++i) { var ch = this.source[i]; if (ch === '8' || ch === '9') { return false; } if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) { return true; } } return true; }; Scanner.prototype.scanNumericLiteral = function () { var start = this.index; var ch = this.source[start]; assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); var num = ''; if (ch !== '.') { num = this.source[this.index++]; ch = this.source[this.index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (num === '0') { if (ch === 'x' || ch === 'X') { ++this.index; return this.scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++this.index; return this.scanBinaryLiteral(start); } if (ch === 'o' || ch === 'O') { return this.scanOctalLiteral(ch, start); } if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { if (this.isImplicitOctalLiteral()) { return this.scanOctalLiteral(ch, start); } } } while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { num += this.source[this.index++]; } ch = this.source[this.index]; } if (ch === '.') { num += this.source[this.index++]; while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { num += this.source[this.index++]; } ch = this.source[this.index]; } if (ch === 'e' || ch === 'E') { num += this.source[this.index++]; ch = this.source[this.index]; if (ch === '+' || ch === '-') { num += this.source[this.index++]; } if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { num += this.source[this.index++]; } } else { this.throwUnexpectedToken(); } } if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { this.throwUnexpectedToken(); } return { type: 6 /* NumericLiteral */, value: parseFloat(num), lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; // path_to_url#sec-literals-string-literals Scanner.prototype.scanStringLiteral = function () { var start = this.index; var quote = this.source[start]; assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); ++this.index; var octal = false; var str = ''; while (!this.eof()) { var ch = this.source[this.index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = this.source[this.index++]; if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'u': if (this.source[this.index] === '{') { ++this.index; str += this.scanUnicodeCodePointEscape(); } else { var unescaped_1 = this.scanHexEscape(ch); if (unescaped_1 === null) { this.throwUnexpectedToken(); } str += unescaped_1; } break; case 'x': var unescaped = this.scanHexEscape(ch); if (unescaped === null) { this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); } str += unescaped; break; case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; case '8': case '9': str += ch; this.tolerateUnexpectedToken(); break; default: if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { var octToDec = this.octalToDecimal(ch); octal = octToDec.octal || octal; str += String.fromCharCode(octToDec.code); } else { str += ch; } break; } } else { ++this.lineNumber; if (ch === '\r' && this.source[this.index] === '\n') { ++this.index; } this.lineStart = this.index; } } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { this.index = start; this.throwUnexpectedToken(); } return { type: 8 /* StringLiteral */, value: str, octal: octal, lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; // path_to_url#sec-template-literal-lexical-components Scanner.prototype.scanTemplate = function () { var cooked = ''; var terminated = false; var start = this.index; var head = (this.source[start] === '`'); var tail = false; var rawOffset = 2; ++this.index; while (!this.eof()) { var ch = this.source[this.index++]; if (ch === '`') { rawOffset = 1; tail = true; terminated = true; break; } else if (ch === '$') { if (this.source[this.index] === '{') { this.curlyStack.push('${'); ++this.index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = this.source[this.index++]; if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': if (this.source[this.index] === '{') { ++this.index; cooked += this.scanUnicodeCodePointEscape(); } else { var restore = this.index; var unescaped_2 = this.scanHexEscape(ch); if (unescaped_2 !== null) { cooked += unescaped_2; } else { this.index = restore; cooked += ch; } } break; case 'x': var unescaped = this.scanHexEscape(ch); if (unescaped === null) { this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); } cooked += unescaped; break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (ch === '0') { if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { // Illegal: \01 \02 and so on this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); } cooked += '\0'; } else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) { // Illegal: \1 \2 this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); } else { cooked += ch; } break; } } else { ++this.lineNumber; if (ch === '\r' && this.source[this.index] === '\n') { ++this.index; } this.lineStart = this.index; } } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { ++this.lineNumber; if (ch === '\r' && this.source[this.index] === '\n') { ++this.index; } this.lineStart = this.index; cooked += '\n'; } else { cooked += ch; } } if (!terminated) { this.throwUnexpectedToken(); } if (!head) { this.curlyStack.pop(); } return { type: 10 /* Template */, value: this.source.slice(start + 1, this.index - rawOffset), cooked: cooked, head: head, tail: tail, lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; // path_to_url#sec-literals-regular-expression-literals Scanner.prototype.testRegExp = function (pattern, flags) { // The BMP character to use as a replacement for astral symbols when // translating an ES6 "u"-flagged pattern to an ES5-compatible // approximation. // Note: replacing with '\uFFFF' enables false positives in unlikely // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid // pattern that would not be detected by this substitution. var astralSubstitute = '\uFFFF'; var tmp = pattern; var self = this; if (flags.indexOf('u') >= 0) { tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) { var codePoint = parseInt($1 || $2, 16); if (codePoint > 0x10FFFF) { self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); } if (codePoint <= 0xFFFF) { return String.fromCharCode(codePoint); } return astralSubstitute; }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute); } // First, detect invalid regular expressions. try { RegExp(tmp); } catch (e) { this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { /* istanbul ignore next */ return null; } }; Scanner.prototype.scanRegExpBody = function () { var ch = this.source[this.index]; assert_1.assert(ch === '/', 'Regular expression literal must start with a slash'); var str = this.source[this.index++]; var classMarker = false; var terminated = false; while (!this.eof()) { ch = this.source[this.index++]; str += ch; if (ch === '\\') { ch = this.source[this.index++]; // path_to_url#sec-literals-regular-expression-literals if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); } str += ch; } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. return str.substr(1, str.length - 2); }; Scanner.prototype.scanRegExpFlags = function () { var str = ''; var flags = ''; while (!this.eof()) { var ch = this.source[this.index]; if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { break; } ++this.index; if (ch === '\\' && !this.eof()) { ch = this.source[this.index]; if (ch === 'u') { ++this.index; var restore = this.index; var char = this.scanHexEscape('u'); if (char !== null) { flags += char; for (str += '\\u'; restore < this.index; ++restore) { str += this.source[restore]; } } else { this.index = restore; flags += 'u'; str += '\\u'; } this.tolerateUnexpectedToken(); } else { str += '\\'; this.tolerateUnexpectedToken(); } } else { flags += ch; str += ch; } } return flags; }; Scanner.prototype.scanRegExp = function () { var start = this.index; var pattern = this.scanRegExpBody(); var flags = this.scanRegExpFlags(); var value = this.testRegExp(pattern, flags); return { type: 9 /* RegularExpression */, value: '', pattern: pattern, flags: flags, regex: value, lineNumber: this.lineNumber, lineStart: this.lineStart, start: start, end: this.index }; }; Scanner.prototype.lex = function () { if (this.eof()) { return { type: 2 /* EOF */, value: '', lineNumber: this.lineNumber, lineStart: this.lineStart, start: this.index, end: this.index }; } var cp = this.source.charCodeAt(this.index); if (character_1.Character.isIdentifierStart(cp)) { return this.scanIdentifier(); } // Very common: ( and ) and ; if (cp === 0x28 || cp === 0x29 || cp === 0x3B) { return this.scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (cp === 0x27 || cp === 0x22) { return this.scanStringLiteral(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (cp === 0x2E) { if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) { return this.scanNumericLiteral(); } return this.scanPunctuator(); } if (character_1.Character.isDecimalDigit(cp)) { return this.scanNumericLiteral(); } // Template literals start with ` (U+0060) for template head // or } (U+007D) for template middle or template tail. if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) { return this.scanTemplate(); } // Possible identifier start in a surrogate pair. if (cp >= 0xD800 && cp < 0xDFFF) { if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) { return this.scanIdentifier(); } } return this.scanPunctuator(); }; return Scanner; }()); exports.Scanner = Scanner; /***/ }, /* 13 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TokenName = {}; exports.TokenName[1 /* BooleanLiteral */] = 'Boolean'; exports.TokenName[2 /* EOF */] = '<end>'; exports.TokenName[3 /* Identifier */] = 'Identifier'; exports.TokenName[4 /* Keyword */] = 'Keyword'; exports.TokenName[5 /* NullLiteral */] = 'Null'; exports.TokenName[6 /* NumericLiteral */] = 'Numeric'; exports.TokenName[7 /* Punctuator */] = 'Punctuator'; exports.TokenName[8 /* StringLiteral */] = 'String'; exports.TokenName[9 /* RegularExpression */] = 'RegularExpression'; exports.TokenName[10 /* Template */] = 'Template'; /***/ }, /* 14 */ /***/ function(module, exports) { "use strict"; // Generated by generate-xhtml-entities.js. DO NOT MODIFY! Object.defineProperty(exports, "__esModule", { value: true }); exports.XHTMLEntities = { quot: '\u0022', amp: '\u0026', apos: '\u0027', gt: '\u003E', nbsp: '\u00A0', iexcl: '\u00A1', cent: '\u00A2', pound: '\u00A3', curren: '\u00A4', yen: '\u00A5', brvbar: '\u00A6', sect: '\u00A7', uml: '\u00A8', copy: '\u00A9', ordf: '\u00AA', laquo: '\u00AB', not: '\u00AC', shy: '\u00AD', reg: '\u00AE', macr: '\u00AF', deg: '\u00B0', plusmn: '\u00B1', sup2: '\u00B2', sup3: '\u00B3', acute: '\u00B4', micro: '\u00B5', para: '\u00B6', middot: '\u00B7', cedil: '\u00B8', sup1: '\u00B9', ordm: '\u00BA', raquo: '\u00BB', frac14: '\u00BC', frac12: '\u00BD', frac34: '\u00BE', iquest: '\u00BF', Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7', Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF', ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', times: '\u00D7', Oslash: '\u00D8', Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF', agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7', egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF', eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', divide: '\u00F7', oslash: '\u00F8', ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF', OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178', fnof: '\u0192', circ: '\u02C6', tilde: '\u02DC', Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398', Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0', Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9', alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8', iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0', rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9', thetasym: '\u03D1', upsih: '\u03D2', piv: '\u03D6', ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A', ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', dagger: '\u2020', Dagger: '\u2021', bull: '\u2022', hellip: '\u2026', permil: '\u2030', prime: '\u2032', Prime: '\u2033', lsaquo: '\u2039', rsaquo: '\u203A', oline: '\u203E', frasl: '\u2044', euro: '\u20AC', image: '\u2111', weierp: '\u2118', real: '\u211C', trade: '\u2122', alefsym: '\u2135', larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5', lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4', forall: '\u2200', part: '\u2202', exist: '\u2203', empty: '\u2205', nabla: '\u2207', isin: '\u2208', notin: '\u2209', ni: '\u220B', prod: '\u220F', sum: '\u2211', minus: '\u2212', lowast: '\u2217', radic: '\u221A', prop: '\u221D', infin: '\u221E', ang: '\u2220', and: '\u2227', or: '\u2228', cap: '\u2229', cup: '\u222A', int: '\u222B', there4: '\u2234', sim: '\u223C', cong: '\u2245', asymp: '\u2248', ne: '\u2260', equiv: '\u2261', le: '\u2264', ge: '\u2265', sub: '\u2282', sup: '\u2283', nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5', lceil: '\u2308', rceil: '\u2309', lfloor: '\u230A', rfloor: '\u230B', loz: '\u25CA', spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666', lang: '\u27E8', rang: '\u27E9' }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var error_handler_1 = __webpack_require__(10); var scanner_1 = __webpack_require__(12); var token_1 = __webpack_require__(13); var Reader = (function () { function Reader() { this.values = []; this.curly = this.paren = -1; } // A function following one of those tokens is an expression. Reader.prototype.beforeFunctionExpression = function (t) { return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0; }; // Determine if forward slash (/) is an operator or part of a regular expression // path_to_url Reader.prototype.isRegexStart = function () { var previous = this.values[this.values.length - 1]; var regex = (previous !== null); switch (previous) { case 'this': case ']': regex = false; break; case ')': var keyword = this.values[this.paren - 1]; regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with'); break; case '}': // Dividing a function by anything makes little sense, // but we have to check for that. regex = false; if (this.values[this.curly - 3] === 'function') { // Anonymous function, e.g. function(){} /42 var check = this.values[this.curly - 4]; regex = check ? !this.beforeFunctionExpression(check) : false; } else if (this.values[this.curly - 4] === 'function') { // Named function, e.g. function f(){} /42/ var check = this.values[this.curly - 5]; regex = check ? !this.beforeFunctionExpression(check) : true; } break; default: break; } return regex; }; Reader.prototype.push = function (token) { if (token.type === 7 /* Punctuator */ || token.type === 4 /* Keyword */) { if (token.value === '{') { this.curly = this.values.length; } else if (token.value === '(') { this.paren = this.values.length; } this.values.push(token.value); } else { this.values.push(null); } }; return Reader; }()); var Tokenizer = (function () { function Tokenizer(code, config) { this.errorHandler = new error_handler_1.ErrorHandler(); this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false; this.scanner = new scanner_1.Scanner(code, this.errorHandler); this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false; this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false; this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false; this.buffer = []; this.reader = new Reader(); } Tokenizer.prototype.errors = function () { return this.errorHandler.errors; }; Tokenizer.prototype.getNextToken = function () { if (this.buffer.length === 0) { var comments = this.scanner.scanComments(); if (this.scanner.trackComment) { for (var i = 0; i < comments.length; ++i) { var e = comments[i]; var value = this.scanner.source.slice(e.slice[0], e.slice[1]); var comment = { type: e.multiLine ? 'BlockComment' : 'LineComment', value: value }; if (this.trackRange) { comment.range = e.range; } if (this.trackLoc) { comment.loc = e.loc; } this.buffer.push(comment); } } if (!this.scanner.eof()) { var loc = void 0; if (this.trackLoc) { loc = { start: { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }, end: {} }; } var startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart(); var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex(); this.reader.push(token); var entry = { type: token_1.TokenName[token.type], value: this.scanner.source.slice(token.start, token.end) }; if (this.trackRange) { entry.range = [token.start, token.end]; } if (this.trackLoc) { loc.end = { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; entry.loc = loc; } if (token.type === 9 /* RegularExpression */) { var pattern = token.pattern; var flags = token.flags; entry.regex = { pattern: pattern, flags: flags }; } this.buffer.push(entry); } } return this.buffer.shift(); }; return Tokenizer; }()); exports.Tokenizer = Tokenizer; /***/ } /******/ ]) }); ; ```
/content/code_sandbox/node_modules/esprima/dist/esprima.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
62,155
```javascript /********************************************************************* * These are commonly used parsers for CSS Values they take a string * * to parse and return a string after it's been converted, if needed * ********************************************************************/ 'use strict'; exports.TYPES = { INTEGER: 1, NUMBER: 2, LENGTH: 3, PERCENT: 4, URL: 5, COLOR: 6, STRING: 7, ANGLE: 8, KEYWORD: 9, NULL_OR_EMPTY_STR: 10 }; /*jslint regexp: true*/ // rough regular expressions var integerRegEx = /^[\-+]?[0-9]+$/; var numberRegEx = /^[\-+]?[0-9]*\.[0-9]+$/; var lengthRegEx = /^(0|[\-+]?[0-9]*\.?[0-9]+(in|cm|em|mm|pt|pc|px))$/; var percentRegEx = /^[\-+]?[0-9]*\.?[0-9]+%$/; var urlRegEx = /^url\(\s*([^\)]*)\s*\)$/; var stringRegEx = /^(\"[^\"]*\"|\'[^\']*\')$/; var colorRegEx1 = /^#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])?$/; var colorRegEx2 = /^rgb\(([^\)]*)\)$/; var colorRegEx3 = /^rgba\(([^\)]*)\)$/; var angleRegEx = /^([\-+]?[0-9]*\.?[0-9]+)(deg|grad|rad)$/; /*jslint regexp: false*/ // This will return one of the above types based on the passed in string exports.valueType = function valueType(val) { if (val === '' || val === null) { return exports.TYPES.NULL_OR_EMPTY_STR; } if (typeof val === 'number') { val = val.toString(); } if (typeof val !== 'string') { return undefined; } if (integerRegEx.test(val)) { return exports.TYPES.INTEGER; } if (numberRegEx.test(val)) { return exports.TYPES.NUMBER; } if (lengthRegEx.test(val)) { return exports.TYPES.LENGTH; } if (percentRegEx.test(val)) { return exports.TYPES.PERCENT; } if (urlRegEx.test(val)) { return exports.TYPES.URL; } if (stringRegEx.test(val)) { return exports.TYPES.STRING; } if (angleRegEx.test(val)) { return exports.TYPES.ANGLE; } if (colorRegEx1.test(val)) { return exports.TYPES.COLOR; } var res = colorRegEx2.exec(val); var parts; if (res !== null) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 3) { return undefined; } if (parts.every(percentRegEx.test.bind(percentRegEx)) || parts.every(integerRegEx.test.bind(integerRegEx))) { return exports.TYPES.COLOR; } return undefined; } res = colorRegEx3.exec(val); if (res !== null) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 4) { return undefined; } if (parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx)) || parts.every(integerRegEx.test.bind(integerRegEx))) { if (numberRegEx.test(parts[3])) { return exports.TYPES.COLOR; } } return undefined; } // could still be a color, one of the standard keyword colors val = val.toLowerCase(); switch (val) { case 'maroon': case 'red': case 'orange': case 'yellow': case 'olive': case 'purple': case 'fuchsia': case 'white': case 'lime': case 'green': case 'navy': case 'blue': case 'aqua': case 'teal': case 'black': case 'silver': case 'gray': // the following are deprecated in CSS3 case 'activeborder': case 'activecaption': case 'appworkspace': case 'background': case 'buttonface': case 'buttonhighlight': case 'buttonshadow': case 'buttontext': case 'captiontext': case 'graytext': case 'highlight': case 'highlighttext': case 'inactiveborder': case 'inactivecaption': case 'inactivecaptiontext': case 'infobackground': case 'infotext': case 'menu': case 'menutext': case 'scrollbar': case 'threeddarkshadow': case 'threedface': case 'threedhighlight': case 'threedlightshadow': case 'threedshadow': case 'window': case 'windowframe': case 'windowtext': return exports.TYPES.COLOR; default: return exports.TYPES.KEYWORD; } }; exports.parseInteger = function parseInteger(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.INTEGER) { return undefined; } return String(parseInt(val, 10)); }; exports.parseNumber = function parseNumber(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.NUMBER && type !== exports.TYPES.INTEGER) { return undefined; } return String(parseFloat(val)); }; exports.parseLength = function parseLength(val) { if (val === 0 || val === '0') { return '0px'; } var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.LENGTH) { return undefined; } return val; }; exports.parsePercent = function parsePercent(val) { if (val === 0 || val === '0') { return '0%'; } var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.PERCENT) { return undefined; } return val; }; // either a length or a percent exports.parseMeasurement = function parseMeasurement(val) { var length = exports.parseLength(val); if (length !== undefined) { return length; } return exports.parsePercent(val); }; exports.parseUrl = function parseUrl(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } var res = urlRegEx.exec(val); // does it match the regex? if (!res) { return undefined; } var str = res[1]; // if it starts with single or double quotes, does it end with the same? if ((str[0] === '"' || str[0] === "'") && str[0] !== str[str.length - 1]) { return undefined; } if (str[0] === '"' || str[0] === "'") { str = str.substr(1, str.length - 2); } var i; for (i = 0; i < str.length; i++) { switch (str[i]) { case '(': case ')': case ' ': case '\t': case '\n': case "'": case '"': return undefined; case '\\': i++; break; } } return 'url(' + str + ')'; }; exports.parseString = function parseString(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.STRING) { return undefined; } var i; for (i = 1; i < val.length - 1; i++) { switch (val[i]) { case val[0]: return undefined; case '\\': i++; while (i < val.length - 1 && /[0-9A-Fa-f]/.test(val[i])) { i++; } break; } } if (i >= val.length) { return undefined; } return val; }; exports.parseColor = function parseColor(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } var red, green, blue, alpha = 1; var parts; var res = colorRegEx1.exec(val); // is it #aaa or #ababab if (res) { var hex = val.substr(1); if (hex.length === 3) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } red = parseInt(hex.substr(0, 2), 16); green = parseInt(hex.substr(2, 2), 16); blue = parseInt(hex.substr(4, 2), 16); return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; } res = colorRegEx2.exec(val); if (res) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 3) { return undefined; } if (parts.every(percentRegEx.test.bind(percentRegEx))) { red = Math.floor(parseFloat(parts[0].slice(0, -1)) * 255 / 100); green = Math.floor(parseFloat(parts[1].slice(0, -1)) * 255 / 100); blue = Math.floor(parseFloat(parts[2].slice(0, -1)) * 255 / 100); } else if (parts.every(integerRegEx.test.bind(integerRegEx))) { red = parseInt(parts[0], 10); green = parseInt(parts[1], 10); blue = parseInt(parts[2], 10); } else { return undefined; } red = Math.min(255, Math.max(0, red)); green = Math.min(255, Math.max(0, green)); blue = Math.min(255, Math.max(0, blue)); return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; } res = colorRegEx3.exec(val); if (res) { parts = res[1].split(/\s*,\s*/); if (parts.length !== 4) { return undefined; } if (parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx))) { red = Math.floor(parseFloat(parts[0].slice(0, -1)) * 255 / 100); green = Math.floor(parseFloat(parts[1].slice(0, -1)) * 255 / 100); blue = Math.floor(parseFloat(parts[2].slice(0, -1)) * 255 / 100); alpha = parseFloat(parts[3]); } else if (parts.slice(0, 3).every(integerRegEx.test.bind(integerRegEx))) { red = parseInt(parts[0], 10); green = parseInt(parts[1], 10); blue = parseInt(parts[2], 10); alpha = parseFloat(parts[3]); } else { return undefined; } if (isNaN(alpha)) { alpha = 1; } red = Math.min(255, Math.max(0, red)); green = Math.min(255, Math.max(0, green)); blue = Math.min(255, Math.max(0, blue)); alpha = Math.min(1, Math.max(0, alpha)); if (alpha === 1) { return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; } return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')'; } if (type === exports.TYPES.COLOR) { return val; } return undefined; }; exports.parseAngle = function parseAngle(val) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.ANGLE) { return undefined; } var res = angleRegEx.exec(val); var flt = parseFloat(res[1]); if (res[2] === 'rad') { flt *= 180 / Math.PI; } else if (res[2] === 'grad') { flt *= 360 / 400; } while (flt < 0) { flt += 360; } while (flt > 360) { flt -= 360; } return flt + 'deg'; }; exports.parseKeyword = function parseKeyword(val, valid_keywords) { var type = exports.valueType(val); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { return val; } if (type !== exports.TYPES.KEYWORD) { return undefined; } val = val.toString().toLowerCase(); var i; for (i = 0; i < valid_keywords.length; i++) { if (valid_keywords[i].toLowerCase() === val) { return valid_keywords[i]; } } return undefined; }; // utility to translate from border-width to borderWidth var dashedToCamelCase = function (dashed) { var i; var camel = ''; var nextCap = false; for (i = 0; i < dashed.length; i++) { if (dashed[i] !== '-') { camel += nextCap ? dashed[i].toUpperCase() : dashed[i]; nextCap = false; } else { nextCap = true; } } return camel; }; exports.dashedToCamelCase = dashedToCamelCase; var is_space = /\s/; var opening_deliminators = ['"', '\'', '(']; var closing_deliminators = ['"', '\'', ')']; // this splits on whitespace, but keeps quoted and parened parts together var getParts = function (str) { var deliminator_stack = []; var length = str.length; var i; var parts = []; var current_part = ''; var opening_index; var closing_index; for (i = 0; i < length; i++) { opening_index = opening_deliminators.indexOf(str[i]); closing_index = closing_deliminators.indexOf(str[i]); if (is_space.test(str[i])) { if (deliminator_stack.length === 0) { if (current_part !== '') { parts.push(current_part); } current_part = ''; } else { current_part += str[i]; } } else { if (str[i] === '\\') { i++; current_part += str[i]; } else { current_part += str[i]; if (closing_index !== -1 && closing_index === deliminator_stack[deliminator_stack.length - 1]) { deliminator_stack.pop(); } else if (opening_index !== -1) { deliminator_stack.push(opening_index); } } } } if (current_part !== '') { parts.push(current_part); } return parts; }; /* * this either returns undefined meaning that it isn't valid * or returns an object where the keys are dashed short * hand properties and the values are the values to set * on them */ exports.shorthandParser = function parse(v, shorthand_for) { var obj = {}; var type = exports.valueType(v); if (type === exports.TYPES.NULL_OR_EMPTY_STR) { Object.keys(shorthand_for).forEach(function (property) { obj[property] = ''; }); return obj; } if (typeof v === 'number') { v = v.toString(); } if (typeof v !== 'string') { return undefined; } if (v.toLowerCase() === 'inherit') { return {}; } var parts = getParts(v); var valid = true; parts.forEach(function (part) { var part_valid = false; Object.keys(shorthand_for).forEach(function (property) { if (shorthand_for[property].isValid(part)) { part_valid = true; obj[property] = part; } }); valid = valid && part_valid; }); if (!valid) { return undefined; } return obj; }; exports.shorthandSetter = function (property, shorthand_for) { return function (v) { var obj = exports.shorthandParser(v, shorthand_for); if (obj === undefined) { return; } //console.log('shorthandSetter for:', property, 'obj:', obj); Object.keys(obj).forEach(function (subprop) { // in case subprop is an implicit property, this will clear // *its* subpropertiesX var camel = dashedToCamelCase(subprop); this[camel] = obj[subprop]; // in case it gets translated into something else (0 -> 0px) obj[subprop] = this[camel]; this.removeProperty(subprop); // don't add in empty properties if (obj[subprop] !== '') { this._values[subprop] = obj[subprop]; } }, this); Object.keys(shorthand_for).forEach(function (subprop) { if (!obj.hasOwnProperty(subprop)) { this.removeProperty(subprop); delete this._values[subprop]; } }, this); // in case the value is something like 'none' that removes all values, // check that the generated one is not empty, first remove the property // if it already exists, then call the shorthandGetter, if it's an empty // string, don't set the property this.removeProperty(property); var calculated = exports.shorthandGetter(property, shorthand_for).call(this); if (calculated !== '') { this._setProperty(property, calculated); } }; }; exports.shorthandGetter = function (property, shorthand_for) { return function () { if (this._values[property] !== undefined) { return this.getPropertyValue(property); } return Object.keys(shorthand_for).map(function (subprop) { return this.getPropertyValue(subprop); }, this).filter(function (value) { return value !== ''; }).join(' '); }; }; // isValid(){1,4} | inherit // if one, it applies to all // if two, the first applies to the top and bottom, and the second to left and right // if three, the first applies to the top, the second to left and right, the third bottom // if four, top, right, bottom, left exports.implicitSetter = function (property_before, property_after, isValid, parser) { property_after = property_after || ''; if (property_after !== '') { property_after = '-' + property_after; } var part_names = ["top","right","bottom","left"]; return function (v) { if (typeof v === 'number') { v = v.toString(); } if (typeof v !== 'string') { return undefined; } var parts; if (v.toLowerCase() === 'inherit' || v === '') { parts = [v]; } else { parts = getParts(v); } if (parts.length < 1 || parts.length > 4) { return undefined; } if (!parts.every(isValid)) { return undefined; } parts = parts.map(function (part) { return parser(part); }); this._setProperty(property_before + property_after, parts.join(' ')); if (parts.length === 1) { parts[1] = parts[0]; } if (parts.length === 2) { parts[2] = parts[0]; } if (parts.length === 3) { parts[3] = parts[1]; } for (var i = 0; i < 4; i++) { var property = property_before + "-" + part_names[i] + property_after; this.removeProperty(property); if (parts[i] !== '') { this._values[property] = parts[i]; } } return v; }; }; // // Companion to implicitSetter, but for the individual parts. // This sets the individual value, and checks to see if all four // sub-parts are set. If so, it sets the shorthand version and removes // the individual parts from the cssText. // exports.subImplicitSetter = function (prefix, part, isValid, parser) { var property = prefix + '-' + part; var subparts = [prefix+"-top", prefix+"-right", prefix+"-bottom", prefix+"-left"]; return function (v) { if (typeof v === 'number') { v = v.toString(); } if (typeof v !== 'string') { return undefined; } if (!isValid(v)) { return undefined; } v = parser(v); this._setProperty(property,v); var parts = []; for (var i = 0; i < 4; i++) { if (this._values[subparts[i]] == null || this._values[subparts[i]] === '') { break; } parts.push(this._values[subparts[i]]); } if (parts.length === 4) { for (i = 0; i < 4; i++) { this.removeProperty(subparts[i]); this._values[subparts[i]] = parts[i]; } this._setProperty(prefix,parts.join(" ")); } return v; }; }; var camel_to_dashed = /[A-Z]/g; /*jslint regexp: true*/ var first_segment = /^\([^\-]\)-/; /*jslint regexp: false*/ var vendor_prefixes = ['o', 'moz', 'ms', 'webkit']; exports.camelToDashed = function (camel_case) { var match; var dashed = camel_case.replace(camel_to_dashed, '-$&').toLowerCase(); match = dashed.match(first_segment); if (match && vendor_prefixes.indexOf(match[1]) !== -1) { dashed = '-' + dashed; } return dashed; }; ```
/content/code_sandbox/node_modules/cssstyle/lib/parsers.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
5,029
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-border-before-style', v); }, get: function () { return this.getPropertyValue('-webkit-border-before-style'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitBorderBeforeStyle.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-marquee-increment', v); }, get: function () { return this.getPropertyValue('-webkit-marquee-increment'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitMarqueeIncrement.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
63
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('stroke-miterlimit', v); }, get: function () { return this.getPropertyValue('stroke-miterlimit'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/strokeMiterlimit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('font-size-adjust', v); }, get: function () { return this.getPropertyValue('font-size-adjust'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/fontSizeAdjust.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-mask-position-y', v); }, get: function () { return this.getPropertyValue('-webkit-mask-position-y'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitMaskPositionY.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-logical-width', v); }, get: function () { return this.getPropertyValue('-webkit-logical-width'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitLogicalWidth.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('outline', v); }, get: function () { return this.getPropertyValue('outline'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/outline.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
55
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-hyphenate-limit-lines', v); }, get: function () { return this.getPropertyValue('-webkit-hyphenate-limit-lines'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitHyphenateLimitLines.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
67
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('letter-spacing', v); }, get: function () { return this.getPropertyValue('letter-spacing'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/letterSpacing.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('border-top-left-radius', v); }, get: function () { return this.getPropertyValue('border-top-left-radius'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/borderTopLeftRadius.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('min-height', v); }, get: function () { return this.getPropertyValue('min-height'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/minHeight.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('stress', v); }, get: function () { return this.getPropertyValue('stress'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/stress.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
55
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-column-rule-width', v); }, get: function () { return this.getPropertyValue('-webkit-column-rule-width'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitColumnRuleWidth.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('text-indent', v); }, get: function () { return this.getPropertyValue('text-indent'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/textIndent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('stroke-width', v); }, get: function () { return this.getPropertyValue('stroke-width'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/strokeWidth.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; var isValid = require('./borderWidth').isValid; module.exports.isValid = isValid; module.exports.definition = { set: function (v) { if (isValid(v)) { this._setProperty('border-top-width', v); } }, get: function () { return this.getPropertyValue('border-top-width'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/borderTopWidth.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
84
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('background-origin', v); }, get: function () { return this.getPropertyValue('background-origin'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/backgroundOrigin.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; var parseColor = require('../parsers').parseColor; module.exports.definition = { set: function (v) { this._setProperty('color', parseColor(v)); }, get: function () { return this.getPropertyValue('color'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/color.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
68
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-text-decorations-in-effect', v); }, get: function () { return this.getPropertyValue('-webkit-text-decorations-in-effect'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitTextDecorationsInEffect.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
67
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('float', v); }, get: function () { return this.getPropertyValue('float'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/cssFloat.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
55
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('background-repeat-x', v); }, get: function () { return this.getPropertyValue('background-repeat-x'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/backgroundRepeatX.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-print-color-adjust', v); }, get: function () { return this.getPropertyValue('-webkit-print-color-adjust'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitPrintColorAdjust.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('list-style-type', v); }, get: function () { return this.getPropertyValue('list-style-type'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/listStyleType.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('marker-end', v); }, get: function () { return this.getPropertyValue('marker-end'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/markerEnd.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; var isValid = module.exports.isValid = require('./borderWidth').isValid; module.exports.definition = { set: function (v) { if (isValid(v)) { this._setProperty('border-right-width', v); } }, get: function () { return this.getPropertyValue('border-right-width'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/borderRightWidth.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
82
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-transition-property', v); }, get: function () { return this.getPropertyValue('-webkit-transition-property'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitTransitionProperty.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('outline-offset', v); }, get: function () { return this.getPropertyValue('outline-offset'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/outlineOffset.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-animation-timing-function', v); }, get: function () { return this.getPropertyValue('-webkit-animation-timing-function'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitAnimationTimingFunction.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
63
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-border-radius', v); }, get: function () { return this.getPropertyValue('-webkit-border-radius'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitBorderRadius.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('text-underline-style', v); }, get: function () { return this.getPropertyValue('text-underline-style'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/textUnderlineStyle.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-max-logical-width', v); }, get: function () { return this.getPropertyValue('-webkit-max-logical-width'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitMaxLogicalWidth.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
63
```javascript 'use strict'; var isValid = require('./borderStyle').isValid; module.exports.isValid = isValid; module.exports.definition = { set: function (v) { if (isValid(v)) { if (v.toLowerCase() === 'none') { v = ''; this.removeProperty('border-bottom-width'); } this._setProperty('border-bottom-style', v); } }, get: function () { return this.getPropertyValue('border-bottom-style'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/borderBottomStyle.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
110
```javascript 'use strict'; var isValid = module.exports.isValid = require('./borderColor').isValid; module.exports.definition = { set: function (v) { if (isValid(v)) { this._setProperty('border-bottom-color', v); } }, get: function () { return this.getPropertyValue('border-bottom-color'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/borderBottomColor.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
82
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-margin-collapse', v); }, get: function () { return this.getPropertyValue('-webkit-margin-collapse'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitMarginCollapse.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('background-clip', v); }, get: function () { return this.getPropertyValue('background-clip'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/backgroundClip.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('pointer-events', v); }, get: function () { return this.getPropertyValue('pointer-events'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/pointerEvents.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('visibility', v); }, get: function () { return this.getPropertyValue('visibility'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/visibility.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
55
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-margin-end', v); }, get: function () { return this.getPropertyValue('-webkit-margin-end'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitMarginEnd.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; var margin = require('./margin.js'); var parsers = require('../parsers.js'); module.exports.definition = { set: parsers.subImplicitSetter('margin', 'left', margin.isValid, margin.parser), get: function () { return this.getPropertyValue('margin-left'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/marginLeft.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
72
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('text-overline-width', v); }, get: function () { return this.getPropertyValue('text-overline-width'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/textOverlineWidth.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
61
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-mask-size', v); }, get: function () { return this.getPropertyValue('-webkit-mask-size'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitMaskSize.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('color-interpolation', v); }, get: function () { return this.getPropertyValue('color-interpolation'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/colorInterpolation.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
59
```javascript 'use strict'; var parseColor = require('../parsers').parseColor; module.exports.definition = { set: function (v) { this._setProperty('-webkit-text-fill-color', parseColor(v)); }, get: function () { return this.getPropertyValue('-webkit-text-fill-color'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/webkitTextFillColor.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
74
```javascript 'use strict'; var parsers = require('../parsers'); // <length> <length>? | inherit // if one, it applies to both horizontal and verical spacing // if two, the first applies to the horizontal and the second applies to vertical spacing var parse = function parse(v) { if (v === '' || v === null) { return undefined; } if (v.toLowerCase() === 'inherit') { return v; } var parts = v.split(/\s+/); if (parts.length !== 1 && parts.length !== 2) { return undefined; } parts.forEach(function (part) { if (parsers.valueType(part) !== parsers.TYPES.LENGTH) { return undefined; } }); return v; }; module.exports.isValid = function isValid(v) { return parse(v) !== undefined; }; module.exports.definition = { set: function (v) { this._setProperty('border-spacing', parse(v)); }, get: function () { return this.getPropertyValue('border-spacing'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/borderSpacing.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
236
```javascript 'use strict'; module.exports.definition = { set: function (v) { this._setProperty('text-anchor', v); }, get: function () { return this.getPropertyValue('text-anchor'); }, enumerable: true, configurable: true }; ```
/content/code_sandbox/node_modules/cssstyle/lib/properties/textAnchor.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
57