From db8d69cce885fe9750b57ff2d88c3a5291b7b18b Mon Sep 17 00:00:00 2001 From: Raphael LANG Date: Wed, 23 Aug 2017 10:16:52 -0400 Subject: [PATCH] Upgrade: update eslint dependency to ^4.0.0 (refs #17) * Remove bypass for https://github.com/eslint/eslint/issues/3307 * Update tests to match updated error ranges * Update browserified eslint to v4.5.0 for codemirror demo page * Update travis configuration to match eslint ^4.0.0 --- .travis.yml | 2 + demos/resources/eslint/eslint.js | 86032 +++++++++++++++-------------- eslint.js | 45 +- package.json | 4 +- test/issues.js | 4 +- 5 files changed, 45218 insertions(+), 40869 deletions(-) diff --git a/.travis.yml b/.travis.yml index 64af7ae..0b5eac2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,3 +3,5 @@ node_js: - "4" - "5" - "6" + - "7" + - "8" diff --git a/demos/resources/eslint/eslint.js b/demos/resources/eslint/eslint.js index 5317984..93783f9 100644 --- a/demos/resources/eslint/eslint.js +++ b/demos/resources/eslint/eslint.js @@ -12665,18 +12665,18 @@ module.exports={ "_args": [ [ { - "raw": "espree@^3.4.0", + "raw": "espree@^3.5.0", "scope": null, "escapedName": "espree", "name": "espree", - "rawSpec": "^3.4.0", - "spec": ">=3.4.0 <4.0.0", + "rawSpec": "^3.5.0", + "spec": ">=3.5.0 <4.0.0", "type": "range" }, - "D:\\users\\r2g\\exps\\eslint-3.19.0" + "D:\\users\\r2g\\exps\\eslint-4.5.0" ] ], - "_from": "espree@>=3.4.0 <4.0.0", + "_from": "espree@>=3.5.0 <4.0.0", "_id": "espree@3.5.0", "_inCache": true, "_location": "/espree", @@ -12692,12 +12692,12 @@ module.exports={ "_npmVersion": "3.10.10", "_phantomChildren": {}, "_requested": { - "raw": "espree@^3.4.0", + "raw": "espree@^3.5.0", "scope": null, "escapedName": "espree", "name": "espree", - "rawSpec": "^3.4.0", - "spec": ">=3.4.0 <4.0.0", + "rawSpec": "^3.5.0", + "spec": ">=3.5.0 <4.0.0", "type": "range" }, "_requiredBy": [ @@ -12706,8 +12706,8 @@ module.exports={ "_resolved": "https://registry.npmjs.org/espree/-/espree-3.5.0.tgz", "_shasum": "98358625bdd055861ea27e2867ea729faf463d8d", "_shrinkwrap": null, - "_spec": "espree@^3.4.0", - "_where": "D:\\users\\r2g\\exps\\eslint-3.19.0", + "_spec": "espree@^3.5.0", + "_where": "D:\\users\\r2g\\exps\\eslint-4.5.0", "author": { "name": "Nicholas C. Zakas", "email": "nicholas+npm@nczconsulting.com" @@ -13670,6 +13670,100 @@ module.exports={ } },{}],2:[function(require,module,exports){ +/** + * @fileoverview Defines a schema for configs. + * @author Sylvan Mably + */ + +"use strict"; + +var baseConfigProperties = { + env: { type: "object" }, + globals: { type: "object" }, + parser: { type: ["string", "null"] }, + parserOptions: { type: "object" }, + plugins: { type: "array" }, + rules: { type: "object" }, + settings: { type: "object" }, + + ecmaFeatures: { type: "object" // deprecated; logs a warning when used + } }; + +var overrideProperties = Object.assign({}, baseConfigProperties, { + files: { + oneOf: [{ type: "string" }, { + type: "array", + items: { type: "string" }, + minItems: 1 + }] + }, + excludedFiles: { + oneOf: [{ type: "string" }, { + type: "array", + items: { type: "string" } + }] + } +}); + +var topLevelConfigProperties = Object.assign({}, baseConfigProperties, { + extends: { type: ["string", "array"] }, + root: { type: "boolean" }, + overrides: { + type: "array", + items: { + type: "object", + properties: overrideProperties, + required: ["files"], + additionalProperties: false + } + } +}); + +var configSchema = { + type: "object", + properties: topLevelConfigProperties, + additionalProperties: false +}; + +module.exports = configSchema; + +},{}],3:[function(require,module,exports){ +/** + * @fileoverview Default config options + * @author Teddy Katz + */ + +"use strict"; + +/** + * Freezes an object and all its nested properties + * @param {Object} obj The object to deeply freeze + * @returns {Object} `obj` after freezing it + */ + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +function deepFreeze(obj) { + if (obj === null || (typeof obj === "undefined" ? "undefined" : _typeof(obj)) !== "object") { + return obj; + } + + Object.keys(obj).map(function (key) { + return obj[key]; + }).forEach(deepFreeze); + return Object.freeze(obj); +} + +module.exports = deepFreeze({ + env: {}, + globals: {}, + rules: {}, + settings: {}, + parser: "espree", + parserOptions: {} +}); + +},{}],4:[function(require,module,exports){ /** * @fileoverview Defines environment settings and globals. * @author Elan Shanker @@ -13778,273 +13872,7 @@ module.exports = { } }; -},{"globals":103}],3:[function(require,module,exports){ -/** - * @fileoverview Configuration applied when a user configuration extends from - * eslint:recommended. - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* eslint sort-keys: ["error", "asc"], quote-props: ["error", "consistent"] */ -/* eslint-disable sort-keys */ - -module.exports = { - parser: "espree", - ecmaFeatures: {}, - - rules: { - - /* eslint-enable sort-keys */ - "accessor-pairs": "off", - "array-bracket-spacing": "off", - "array-callback-return": "off", - "arrow-body-style": "off", - "arrow-parens": "off", - "arrow-spacing": "off", - "block-scoped-var": "off", - "block-spacing": "off", - "brace-style": "off", - "callback-return": "off", - "camelcase": "off", - "capitalized-comments": "off", - "class-methods-use-this": "off", - "comma-dangle": "off", - "comma-spacing": "off", - "comma-style": "off", - "complexity": "off", - "computed-property-spacing": "off", - "consistent-return": "off", - "consistent-this": "off", - "constructor-super": "error", - "curly": "off", - "default-case": "off", - "dot-location": "off", - "dot-notation": "off", - "eol-last": "off", - "eqeqeq": "off", - "func-call-spacing": "off", - "func-name-matching": "off", - "func-names": "off", - "func-style": "off", - "generator-star-spacing": "off", - "global-require": "off", - "guard-for-in": "off", - "handle-callback-err": "off", - "id-blacklist": "off", - "id-length": "off", - "id-match": "off", - "indent": "off", - "init-declarations": "off", - "jsx-quotes": "off", - "key-spacing": "off", - "keyword-spacing": "off", - "line-comment-position": "off", - "linebreak-style": "off", - "lines-around-comment": "off", - "lines-around-directive": "off", - "max-depth": "off", - "max-len": "off", - "max-lines": "off", - "max-nested-callbacks": "off", - "max-params": "off", - "max-statements": "off", - "max-statements-per-line": "off", - "multiline-ternary": "off", - "new-cap": "off", - "new-parens": "off", - "newline-after-var": "off", - "newline-before-return": "off", - "newline-per-chained-call": "off", - "no-alert": "off", - "no-array-constructor": "off", - "no-await-in-loop": "off", - "no-bitwise": "off", - "no-caller": "off", - "no-case-declarations": "error", - "no-catch-shadow": "off", - "no-class-assign": "error", - "no-compare-neg-zero": "off", - "no-cond-assign": "error", - "no-confusing-arrow": "off", - "no-console": "error", - "no-const-assign": "error", - "no-constant-condition": "error", - "no-continue": "off", - "no-control-regex": "error", - "no-debugger": "error", - "no-delete-var": "error", - "no-div-regex": "off", - "no-dupe-args": "error", - "no-dupe-class-members": "error", - "no-dupe-keys": "error", - "no-duplicate-case": "error", - "no-duplicate-imports": "off", - "no-else-return": "off", - "no-empty": "error", - "no-empty-character-class": "error", - "no-empty-function": "off", - "no-empty-pattern": "error", - "no-eq-null": "off", - "no-eval": "off", - "no-ex-assign": "error", - "no-extend-native": "off", - "no-extra-bind": "off", - "no-extra-boolean-cast": "error", - "no-extra-label": "off", - "no-extra-parens": "off", - "no-extra-semi": "error", - "no-fallthrough": "error", - "no-floating-decimal": "off", - "no-func-assign": "error", - "no-global-assign": "error", - "no-implicit-coercion": "off", - "no-implicit-globals": "off", - "no-implied-eval": "off", - "no-inline-comments": "off", - "no-inner-declarations": "error", - "no-invalid-regexp": "error", - "no-invalid-this": "off", - "no-irregular-whitespace": "error", - "no-iterator": "off", - "no-label-var": "off", - "no-labels": "off", - "no-lone-blocks": "off", - "no-lonely-if": "off", - "no-loop-func": "off", - "no-magic-numbers": "off", - "no-mixed-operators": "off", - "no-mixed-requires": "off", - "no-mixed-spaces-and-tabs": "error", - "no-multi-assign": "off", - "no-multi-spaces": "off", - "no-multi-str": "off", - "no-multiple-empty-lines": "off", - "no-native-reassign": "off", - "no-negated-condition": "off", - "no-negated-in-lhs": "off", - "no-nested-ternary": "off", - "no-new": "off", - "no-new-func": "off", - "no-new-object": "off", - "no-new-require": "off", - "no-new-symbol": "error", - "no-new-wrappers": "off", - "no-obj-calls": "error", - "no-octal": "error", - "no-octal-escape": "off", - "no-param-reassign": "off", - "no-path-concat": "off", - "no-plusplus": "off", - "no-process-env": "off", - "no-process-exit": "off", - "no-proto": "off", - "no-prototype-builtins": "off", - "no-redeclare": "error", - "no-regex-spaces": "error", - "no-restricted-globals": "off", - "no-restricted-imports": "off", - "no-restricted-modules": "off", - "no-restricted-properties": "off", - "no-restricted-syntax": "off", - "no-return-assign": "off", - "no-return-await": "off", - "no-script-url": "off", - "no-self-assign": "error", - "no-self-compare": "off", - "no-sequences": "off", - "no-shadow": "off", - "no-shadow-restricted-names": "off", - "no-spaced-func": "off", - "no-sparse-arrays": "error", - "no-sync": "off", - "no-tabs": "off", - "no-template-curly-in-string": "off", - "no-ternary": "off", - "no-this-before-super": "error", - "no-throw-literal": "off", - "no-trailing-spaces": "off", - "no-undef": "error", - "no-undef-init": "off", - "no-undefined": "off", - "no-underscore-dangle": "off", - "no-unexpected-multiline": "error", - "no-unmodified-loop-condition": "off", - "no-unneeded-ternary": "off", - "no-unreachable": "error", - "no-unsafe-finally": "error", - "no-unsafe-negation": "error", - "no-unused-expressions": "off", - "no-unused-labels": "error", - "no-unused-vars": "error", - "no-use-before-define": "off", - "no-useless-call": "off", - "no-useless-computed-key": "off", - "no-useless-concat": "off", - "no-useless-constructor": "off", - "no-useless-escape": "off", - "no-useless-rename": "off", - "no-useless-return": "off", - "no-var": "off", - "no-void": "off", - "no-warning-comments": "off", - "no-whitespace-before-property": "off", - "no-with": "off", - "nonblock-statement-body-position": "off", - "object-curly-newline": "off", - "object-curly-spacing": ["off", "never"], - "object-property-newline": "off", - "object-shorthand": "off", - "one-var": "off", - "one-var-declaration-per-line": "off", - "operator-assignment": "off", - "operator-linebreak": "off", - "padded-blocks": "off", - "prefer-arrow-callback": "off", - "prefer-const": "off", - "prefer-destructuring": "off", - "prefer-numeric-literals": "off", - "prefer-promise-reject-errors": "off", - "prefer-reflect": "off", - "prefer-rest-params": "off", - "prefer-spread": "off", - "prefer-template": "off", - "quote-props": "off", - "quotes": "off", - "radix": "off", - "require-await": "off", - "require-jsdoc": "off", - "require-yield": "error", - "rest-spread-spacing": "off", - "semi": "off", - "semi-spacing": "off", - "sort-imports": "off", - "sort-keys": "off", - "sort-vars": "off", - "space-before-blocks": "off", - "space-before-function-paren": "off", - "space-in-parens": "off", - "space-infix-ops": "off", - "space-unary-ops": "off", - "spaced-comment": "off", - "strict": "off", - "symbol-description": "off", - "template-curly-spacing": "off", - "template-tag-spacing": "off", - "unicode-bom": "off", - "use-isnan": "error", - "valid-jsdoc": "off", - "valid-typeof": "error", - "vars-on-top": "off", - "wrap-iife": "off", - "wrap-regex": "off", - "yield-star-spacing": "off", - "yoda": "off" - } -}; - -},{}],4:[function(require,module,exports){ +},{"globals":81}],5:[function(require,module,exports){ module.exports={ "rules": { "generator-star": ["generator-star-spacing"], @@ -14068,7176 +13896,10465 @@ module.exports={ } } -},{}],5:[function(require,module,exports){ -(function (global){ +},{}],6:[function(require,module,exports){ 'use strict'; -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: - -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; +var KEYWORDS = ['multipleOf', 'maximum', 'exclusiveMaximum', 'minimum', 'exclusiveMinimum', 'maxLength', 'minLength', 'pattern', 'additionalItems', 'maxItems', 'minItems', 'uniqueItems', 'maxProperties', 'minProperties', 'required', 'additionalProperties', 'enum', 'format', 'const']; + +module.exports = function (metaSchema, keywordsJsonPointers) { + for (var i = 0; i < keywordsJsonPointers.length; i++) { + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + var segments = keywordsJsonPointers[i].split('/'); + var keywords = metaSchema; + var j; + for (j = 1; j < segments.length; j++) { + keywords = keywords[segments[j]]; + }for (j = 0; j < KEYWORDS.length; j++) { + var key = KEYWORDS[j]; + var schema = keywords[key]; + if (schema) { + keywords[key] = { + anyOf: [schema, { $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }] + }; + } + } } - var x = a.length; - var y = b.length; + return metaSchema; +}; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } +},{}],7:[function(require,module,exports){ +'use strict'; - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var compileSchema = require('./compile'), + resolve = require('./compile/resolve'), + Cache = require('./cache'), + SchemaObject = require('./compile/schema_obj'), + stableStringify = require('json-stable-stringify'), + formats = require('./compile/formats'), + rules = require('./compile/rules'), + $dataMetaSchema = require('./$data'), + patternGroups = require('./patternGroups'), + util = require('./compile/util'), + co = require('co'); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = require('./compile/async'); +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; + +var errorClasses = require('./compile/error_classes'); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema'; + +var META_IGNORE_OPTIONS = ['removeAdditional', 'useDefaults', 'coerceTypes']; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + var schemaUriFormat = this._schemaUriFormat = this._formats['uri-reference']; + this._schemaUriFormatFunc = function (str) { + return schemaUriFormat.test(str); + }; + + this._cache = opts.cache || new Cache(); + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + + if (opts.formats) addInitialFormats(this); + addDraft6MetaSchema(this); + if (_typeof(opts.meta) == 'object') this.addMetaSchema(opts.meta); + addInitialSchemas(this); + if (opts.patternGroups) patternGroups(this); } -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); + +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); } - return !!(b != null && b._isBuffer); + + var valid = v(data); + if (v.$async === true) return this._opts.async == '*' ? co(valid) : valid; + this.errors = v.errors; + return valid; } -// based on node assert, original notice: +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)) { + for (var i = 0; i < schema.length; i++) { + this.addSchema(schema[i], undefined, _skipValidation, _meta); + }return; + } + var id = this._getId(schema); + if (id !== undefined && typeof id != 'string') throw new Error('schema id must be string'); + key = resolve.normalizeId(key || id); + checkUnique(this, key); + this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true); +} -var util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); +/** + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @this Ajv + * @param {Object} schema schema object + * @param {String} key optional schema key + * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema + */ +function addMetaSchema(schema, key, skipValidation) { + this.addSchema(schema, key, skipValidation, true); } -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { + +/** + * Validate schema + * @this Ajv + * @param {Object} schema schema to validate + * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid + * @return {Boolean} true if schema is valid + */ +function validateSchema(schema, throwOrLogError) { + var $schema = schema.$schema; + if ($schema !== undefined && typeof $schema != 'string') throw new Error('$schema must be a string'); + $schema = $schema || this._opts.defaultMeta || defaultMeta(this); + if (!$schema) { + console.warn('meta-schema not available'); + this.errors = null; return true; } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; + var currentUriFormat = this._formats.uri; + this._formats.uri = typeof currentUriFormat == 'function' ? this._schemaUriFormatFunc : this._schemaUriFormat; + var valid; + try { + valid = this.validate($schema, schema); + } finally { + this._formats.uri = currentUriFormat; } - return false; + if (!valid && throwOrLogError) { + var message = 'schema is invalid: ' + this.errorsText(); + if (this._opts.validateSchema == 'log') console.error(message);else throw new Error(message); + } + return valid; } -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) +function defaultMeta(self) { + var meta = self._opts.meta; + self._opts.defaultMeta = (typeof meta === 'undefined' ? 'undefined' : _typeof(meta)) == 'object' ? self._getId(meta) || meta : self.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined; + return self._opts.defaultMeta; +} -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; +/** + * Get compiled schema from the instance by `key` or `ref`. + * @this Ajv + * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). + */ +function getSchema(keyRef) { + var schemaObj = _getSchemaObj(this, keyRef); + switch (typeof schemaObj === 'undefined' ? 'undefined' : _typeof(schemaObj)) { + case 'object': + return schemaObj.validate || this._compile(schemaObj); + case 'string': + return this.getSchema(schemaObj); + case 'undefined': + return _getSchemaFragment(this, keyRef); } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; } -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - this.stack = out; - } +function _getSchemaFragment(self, ref) { + var res = resolve.schema.call(self, { schema: {} }, ref); + if (res) { + var schema = res.schema, + root = res.root, + baseId = res.baseId; + var v = compileSchema.call(self, schema, root, undefined, baseId); + self._fragments[ref] = new SchemaObject({ + ref: ref, + fragment: true, + schema: schema, + root: root, + baseId: baseId, + validate: v + }); + return v; } -}; +} -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); +function _getSchemaObj(self, keyRef) { + keyRef = resolve.normalizeId(keyRef); + return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; +} -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; +/** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @this Ajv + * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object + */ +function removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + _removeAllSchemas(this, this._schemas, schemaKeyRef); + _removeAllSchemas(this, this._refs, schemaKeyRef); + return; } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); + switch (typeof schemaKeyRef === 'undefined' ? 'undefined' : _typeof(schemaKeyRef)) { + case 'undefined': + _removeAllSchemas(this, this._schemas); + _removeAllSchemas(this, this._refs); + this._cache.clear(); + return; + case 'string': + var schemaObj = _getSchemaObj(this, schemaKeyRef); + if (schemaObj) this._cache.del(schemaObj.cacheKey); + delete this._schemas[schemaKeyRef]; + delete this._refs[schemaKeyRef]; + return; + case 'object': + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; + this._cache.del(cacheKey); + var id = this._getId(schemaKeyRef); + if (id) { + id = resolve.normalizeId(id); + delete this._schemas[id]; + delete this._refs[id]; + } } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; } -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); + +function _removeAllSchemas(self, schemas, regex) { + for (var keyRef in schemas) { + var schemaObj = schemas[keyRef]; + if (!schemaObj.meta && (!regex || regex.test(keyRef))) { + self._cache.del(schemaObj.cacheKey); + delete schemas[keyRef]; + } + } } -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. +/* @this Ajv */ +function _addSchema(schema, skipValidation, meta, shouldAddSchema) { + if ((typeof schema === 'undefined' ? 'undefined' : _typeof(schema)) != 'object' && typeof schema != 'boolean') throw new Error('schema should be object or boolean'); + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schema) : schema; + var cached = this._cache.get(cacheKey); + if (cached) return cached; -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. + shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} + var id = resolve.normalizeId(this._getId(schema)); + if (id && shouldAddSchema) checkUnique(this, id); -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; + var willValidate = this._opts.validateSchema !== false && !skipValidation; + var recursiveMeta; + if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) this.validateSchema(schema, true); -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. + var localRefs = resolve.ids.call(this, schema); -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; + var schemaObj = new SchemaObject({ + id: id, + schema: schema, + localRefs: localRefs, + cacheKey: cacheKey, + meta: meta + }); -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); + if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; + this._cache.put(cacheKey, schemaObj); -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; + if (willValidate && recursiveMeta) this.validateSchema(schema, true); -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); + return schemaObj; +} -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); +/* @this Ajv */ +function _compile(schemaObj, root) { + if (schemaObj.compiling) { + schemaObj.validate = callValidate; + callValidate.schema = schemaObj.schema; + callValidate.errors = null; + callValidate.root = root ? root : callValidate; + if (schemaObj.schema.$async === true) callValidate.$async = true; + return callValidate; } -}; + schemaObj.compiling = true; -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); + var currentOpts; + if (schemaObj.meta) { + currentOpts = this._opts; + this._opts = this._metaOpts; } -}; -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + var v; + try { + v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); + } finally { + schemaObj.compiling = false; + if (schemaObj.meta) this._opts = currentOpts; + } + + schemaObj.validate = v; + schemaObj.refs = v.refs; + schemaObj.refVal = v.refVal; + schemaObj.root = v.root; + return v; + + function callValidate() { + var _validate = schemaObj.validate; + var result = _validate.apply(null, arguments); + callValidate.errors = _validate.errors; + return result; } -}; - -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; +} - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); +function chooseGetId(opts) { + switch (opts.schemaId) { + case '$id': + return _get$Id; + case 'id': + return _getId; + default: + return _get$IdOrId; + } +} - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; +function _getId(schema) { + if (schema.$id) console.warn('schema $id ignored', schema.$id); + return schema.id; +} - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; +function _get$Id(schema) { + if (schema.id) console.warn('schema id ignored', schema.id); + return schema.$id; +} - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } - } +function _get$IdOrId(schema) { + if (schema.$id && schema.id && schema.$id != schema.id) throw new Error('schema $id is different from id'); + return schema.$id || schema.id; +} - memos.actual.push(actual); - memos.expected.push(expected); +/** + * Convert array of error message objects to string + * @this Ajv + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; - return objEquiv(actual, expected, strict, memos); + var text = ''; + for (var i = 0; i < errors.length; i++) { + var e = errors[i]; + if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; } + return text.slice(0, -separator.length); } -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; +/** + * Add custom format + * @this Ajv + * @param {String} name format name + * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) + */ +function addFormat(name, format) { + if (typeof format == 'string') format = new RegExp(format); + this._formats[name] = format; } -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; +function addDraft6MetaSchema(self) { + var $dataSchema; + if (self._opts.$data) { + $dataSchema = require('./refs/$data.json'); + self.addMetaSchema($dataSchema, $dataSchema.$id, true); + } + if (self._opts.meta === false) return; + var metaSchema = require('./refs/json-schema-draft-06.json'); + if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); + self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); + self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; } -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); +function addInitialSchemas(self) { + var optsSchemas = self._opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);else for (var key in optsSchemas) { + self.addSchema(optsSchemas[key], key); } -}; +} -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); +function addInitialFormats(self) { + for (var name in self._opts.formats) { + var format = self._opts.formats[name]; + self.addFormat(name, format); } } +function checkUnique(self, id) { + if (self._schemas[id] || self._refs[id]) throw new Error('schema with key or id "' + id + '" already exists'); +} -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); +function getMetaSchemaOptions(self) { + var metaOpts = util.copy(self._opts); + for (var i = 0; i < META_IGNORE_OPTIONS.length; i++) { + delete metaOpts[META_IGNORE_OPTIONS[i]]; + }return metaOpts; +} -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } +},{"./$data":6,"./cache":8,"./compile":13,"./compile/async":10,"./compile/error_classes":11,"./compile/formats":12,"./compile/resolve":14,"./compile/rules":15,"./compile/schema_obj":16,"./compile/util":18,"./keyword":42,"./patternGroups":43,"./refs/$data.json":44,"./refs/json-schema-draft-06.json":46,"co":50,"json-stable-stringify":85}],8:[function(require,module,exports){ +'use strict'; + +var Cache = module.exports = function Cache() { + this._cache = {}; }; -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; }; -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; +}; - try { - if (actual instanceof expected) { - return true; - } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } +},{}],9:[function(require,module,exports){ +'use strict'; - if (Error.isPrototypeOf(expected)) { - return false; - } +//all requires must be explicit because browserify won't work with dynamic requires - return expected.call({}, actual) === true; -} +module.exports = { + '$ref': require('../dotjs/ref'), + allOf: require('../dotjs/allOf'), + anyOf: require('../dotjs/anyOf'), + const: require('../dotjs/const'), + contains: require('../dotjs/contains'), + dependencies: require('../dotjs/dependencies'), + 'enum': require('../dotjs/enum'), + format: require('../dotjs/format'), + items: require('../dotjs/items'), + maximum: require('../dotjs/_limit'), + minimum: require('../dotjs/_limit'), + maxItems: require('../dotjs/_limitItems'), + minItems: require('../dotjs/_limitItems'), + maxLength: require('../dotjs/_limitLength'), + minLength: require('../dotjs/_limitLength'), + maxProperties: require('../dotjs/_limitProperties'), + minProperties: require('../dotjs/_limitProperties'), + multipleOf: require('../dotjs/multipleOf'), + not: require('../dotjs/not'), + oneOf: require('../dotjs/oneOf'), + pattern: require('../dotjs/pattern'), + properties: require('../dotjs/properties'), + propertyNames: require('../dotjs/propertyNames'), + required: require('../dotjs/required'), + uniqueItems: require('../dotjs/uniqueItems'), + validate: require('../dotjs/validate') +}; + +},{"../dotjs/_limit":19,"../dotjs/_limitItems":20,"../dotjs/_limitLength":21,"../dotjs/_limitProperties":22,"../dotjs/allOf":23,"../dotjs/anyOf":24,"../dotjs/const":25,"../dotjs/contains":26,"../dotjs/dependencies":28,"../dotjs/enum":29,"../dotjs/format":30,"../dotjs/items":31,"../dotjs/multipleOf":32,"../dotjs/not":33,"../dotjs/oneOf":34,"../dotjs/pattern":35,"../dotjs/properties":36,"../dotjs/propertyNames":37,"../dotjs/ref":38,"../dotjs/required":39,"../dotjs/uniqueItems":40,"../dotjs/validate":41}],10:[function(require,module,exports){ +'use strict'; -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; - } - return error; -} +var MissingRefError = require('./error_classes').MissingRef; -function _throws(shouldThrow, block, expected, message) { - var actual; +module.exports = compileAsync; - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } +/** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. + * @return {Promise} promise that resolves with a validating function. + */ +function compileAsync(schema, meta, callback) { + /* eslint no-shadow: 0 */ + /* global Promise */ + /* jshint validthis: true */ + var self = this; + if (typeof this._opts.loadSchema != 'function') throw new Error('options.loadSchema should be a function'); - if (typeof expected === 'string') { - message = expected; - expected = null; + if (typeof meta == 'function') { + callback = meta; + meta = undefined; } - actual = _tryBlock(block); - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); + var p = loadMetaSchemaOf(schema).then(function () { + var schemaObj = self._addSchema(schema, undefined, meta); + return schemaObj.validate || _compileAsync(schemaObj); + }); - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); + if (callback) { + p.then(function (v) { + callback(null, v); + }, callback); } - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; + return p; - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); + function loadMetaSchemaOf(sch) { + var $schema = sch.$schema; + return $schema && !self.getSchema($schema) ? compileAsync.call(self, { $ref: $schema }, true) : Promise.resolve(); } - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} + function _compileAsync(schemaObj) { + try { + return self._compile(schemaObj); + } catch (e) { + if (e instanceof MissingRefError) return loadMissingSchema(e); + throw e; + } -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); + function loadMissingSchema(e) { + var ref = e.missingSchema; + if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; + var schemaPromise = self._loadingSchemas[ref]; + if (!schemaPromise) { + schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); + schemaPromise.then(removePromise, removePromise); + } -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; + return schemaPromise.then(function (sch) { + if (!added(ref)) { + return loadMetaSchemaOf(sch).then(function () { + if (!added(ref)) self.addSchema(sch, ref, undefined, meta); + }); + } + }).then(function () { + return _compileAsync(schemaObj); + }); -assert.ifError = function(err) { if (err) throw err; }; + function removePromise() { + delete self._loadingSchemas[ref]; + } -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); + function added(ref) { + return self._refs[ref] || self._schemas[ref]; + } + } } - return keys; -}; +} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":129}],6:[function(require,module,exports){ +},{"./error_classes":11}],11:[function(require,module,exports){ 'use strict'; -var copy = require('es5-ext/object/copy') - , normalizeOptions = require('es5-ext/object/normalize-options') - , ensureCallable = require('es5-ext/object/valid-callable') - , map = require('es5-ext/object/map') - , callable = require('es5-ext/object/valid-callable') - , validValue = require('es5-ext/object/valid-value') - - , bind = Function.prototype.bind, defineProperty = Object.defineProperty - , hasOwnProperty = Object.prototype.hasOwnProperty - , define; - -define = function (name, desc, options) { - var value = validValue(desc) && callable(desc.value), dgs; - dgs = copy(desc); - delete dgs.writable; - delete dgs.value; - dgs.get = function () { - if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value; - desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this); - defineProperty(this, name, desc); - return this[name]; - }; - return dgs; +var resolve = require('./resolve'); + +module.exports = { + Validation: errorSubclass(ValidationError), + MissingRef: errorSubclass(MissingRefError) }; -module.exports = function (props/*, options*/) { - var options = normalizeOptions(arguments[1]); - if (options.resolveContext != null) ensureCallable(options.resolveContext); - return map(props, function (desc, name) { return define(name, desc, options); }); +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; +} + +MissingRefError.message = function (baseId, ref) { + return 'can\'t resolve reference ' + ref + ' from id ' + baseId; }; -},{"es5-ext/object/copy":34,"es5-ext/object/map":43,"es5-ext/object/normalize-options":44,"es5-ext/object/valid-callable":49,"es5-ext/object/valid-value":51}],7:[function(require,module,exports){ +function MissingRefError(baseId, ref, message) { + this.message = message || MissingRefError.message(baseId, ref); + this.missingRef = resolve.url(baseId, ref); + this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); +} + +function errorSubclass(Subclass) { + Subclass.prototype = Object.create(Error.prototype); + Subclass.prototype.constructor = Subclass; + return Subclass; +} + +},{"./resolve":14}],12:[function(require,module,exports){ 'use strict'; -var assign = require('es5-ext/object/assign') - , normalizeOpts = require('es5-ext/object/normalize-options') - , isCallable = require('es5-ext/object/is-callable') - , contains = require('es5-ext/string/#/contains') +var util = require('./util'); + +var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/; +var DAYS = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i; +var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i; +var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +// uri-template: https://tools.ietf.org/html/rfc6570 +var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$|^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} - , d; +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+-.]*)(?::|\/)\/?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: hostname, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var month = +matches[1]; + var day = +matches[2]; + return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month]; +} -d = module.exports = function (dscr, value/*, options*/) { - var c, e, w, options, desc; - if ((arguments.length < 2) || (typeof dscr !== 'string')) { - options = value; - value = dscr; - dscr = null; - } else { - options = arguments[2]; - } - if (dscr == null) { - c = w = true; - e = false; - } else { - c = contains.call(dscr, 'c'); - e = contains.call(dscr, 'e'); - w = contains.call(dscr, 'w'); - } +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; - desc = { value: value, configurable: c, enumerable: e, writable: w }; - return !options ? desc : assign(normalizeOpts(options), desc); -}; + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone); +} -d.gs = function (dscr, get, set/*, options*/) { - var c, e, options, desc; - if (typeof dscr !== 'string') { - options = set; - set = get; - get = dscr; - dscr = null; - } else { - options = arguments[3]; - } - if (get == null) { - get = undefined; - } else if (!isCallable(get)) { - options = get; - get = set = undefined; - } else if (set == null) { - set = undefined; - } else if (!isCallable(set)) { - options = set; - set = undefined; - } - if (dscr == null) { - c = true; - e = false; - } else { - c = contains.call(dscr, 'c'); - e = contains.call(dscr, 'e'); - } +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} - desc = { get: get, set: set, configurable: c, enumerable: e }; - return !options ? desc : assign(normalizeOpts(options), desc); -}; +function hostname(str) { + // https://tools.ietf.org/html/rfc1034#section-3.5 + // https://tools.ietf.org/html/rfc1123#section-2 + return str.length <= 255 && HOSTNAME.test(str); +} -},{"es5-ext/object/assign":31,"es5-ext/object/is-callable":37,"es5-ext/object/normalize-options":44,"es5-ext/string/#/contains":52}],8:[function(require,module,exports){ -(function (process){ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } +} -/** - * Colors. - */ +},{"./util":18}],13:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var resolve = require('./resolve'), + util = require('./util'), + errorClasses = require('./error_classes'), + stableStringify = require('json-stable-stringify'); -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +var validateGenerator = require('../dotjs/validate'); /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * Functions below are used inside compiled validations function */ -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } +var co = require('co'); +var ucs2length = util.ucs2length; +var equal = require('fast-deep-equal'); - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this, + opts = this._opts, + refVal = [undefined], + refs = {}, + patterns = [], + patternsHash = {}, + defaults = [], + defaultsHash = {}, + customRules = []; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return compilation.callValidate = callValidate; + + var formats = this._formats; + var RULES = this.RULES; -exports.formatters.j = function(v) { try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + function callValidate() { + var validate = compilation.validate; + var result = validate.apply(null, arguments); + callValidate.errors = validate.errors; + return result; } -}; + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || _root && _root.schema == _schema; + if (_root.schema != root.schema) return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + self: self + }); -/** - * Colorize log arguments if enabled. - * - * @api public - */ + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode; -function formatArgs(args) { - var useColors = this.useColors; + if (opts.processCode) sourceCode = opts.processCode(sourceCode); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function('self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'co', 'equal', 'ucs2length', 'ValidationError', sourceCode); - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + validate = makeValidate(self, RULES, formats, root, refVal, defaults, customRules, co, equal, ucs2length, ValidationError); - if (!useColors) return; + refVal[0] = validate; + } catch (e) { + console.error('Error compiling schema, function code:', sourceCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + return validate; + } - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } } - }); - args.splice(lastC, 0, c); -} + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId); + } + } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + function removeLocalRef(ref) { + delete refs[ref]; + } -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return (typeof refVal === 'undefined' ? 'undefined' : _typeof(refVal)) == 'object' || typeof refVal == 'boolean' ? { code: code, schema: refVal, inline: true } : { code: code, $async: refVal && refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value === 'undefined' ? 'undefined' : _typeof(value)) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + var validateSchema = rule.definition.validateSchema; + if (validateSchema && self._opts.validateSchema !== false) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') console.error(message);else throw new Error(message); + } + } + + var compile = rule.definition.compile, + inline = rule.definition.inline, + macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); } else { - exports.storage.debug = namespaces; + validate = rule.definition.validate; + if (!validate) return; } - } catch(e) {} -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + if (validate === undefined) throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} + var index = customRules.length; + customRules[index] = validate; - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; + return { + code: 'customRule' + index, + validate: validate + }; } +} - return r; +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; } /** - * Enable namespaces listed in `localStorage.debug` initially. + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID */ - -exports.enable(load()); +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i = 0; i < this._compilations.length; i++) { + var c = this._compilations[i]; + if (c.schema == schema && c.root == root && c.baseId == baseId) return i; + } + return -1; +} -function localstorage() { - try { - return window.localStorage; - } catch (e) {} +function patternCode(i, patterns) { + return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');'; } -}).call(this,require('_process')) -},{"./debug":9,"_process":123}],9:[function(require,module,exports){ +function defaultCode(i) { + return 'var default' + i + ' = defaults[' + i + '];'; +} -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ +function refValCode(i, refVal) { + return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];'; +} -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); +function customRuleCode(i) { + return 'var customRule' + i + ' = customRules[' + i + '];'; +} -/** - * The currently active debug mode names, and names to skip. - */ +function vars(arr, statement) { + if (!arr.length) return ''; + var code = ''; + for (var i = 0; i < arr.length; i++) { + code += statement(i, arr); + }return code; +} -exports.names = []; -exports.skips = []; +},{"../dotjs/validate":41,"./error_classes":11,"./resolve":14,"./util":18,"co":50,"fast-deep-equal":78,"json-stable-stringify":85}],14:[function(require,module,exports){ +'use strict'; -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -exports.formatters = {}; +var url = require('url'), + equal = require('fast-deep-equal'), + util = require('./util'), + SchemaObject = require('./schema_obj'), + traverse = require('json-schema-traverse'); -/** - * Previous log timestamp. - */ +module.exports = resolve; -var prevTime; +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private + * [resolve and compile the references ($ref)] + * @this Ajv + * @param {Function} compile reference to schema compilation funciton (localCompile) + * @param {Object} root object with information about the root schema for the current schema + * @param {String} ref reference to resolve + * @return {Object|Function} schema object (if the schema can be inlined) or validation function */ +function resolve(compile, root, ref) { + /* jshint validthis: true */ + var refVal = this._refs[ref]; + if (typeof refVal == 'string') { + if (this._refs[refVal]) refVal = this._refs[refVal];else return resolve.call(this, compile, root, refVal); + } -function selectColor(namespace) { - var hash = 0, i; + refVal = refVal || this._schemas[ref]; + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal); + } - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; } - return exports.colors[Math.abs(hash) % exports.colors.length]; + if (schema instanceof SchemaObject) { + v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); + } else if (schema !== undefined) { + v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, undefined, baseId); + } + + return v; } /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ + * Resolve schema, its root and baseId + * @this Ajv + * @param {Object} root root object with properties schema, refVal, refs + * @param {String} ref reference to resolve + * @return {Object} object with properties schema, root, baseId + */ +function resolveSchema(root, ref) { + /* jshint validthis: true */ + var p = url.parse(ref, false, true), + refPath = _getFullPath(p), + baseId = getFullPath(this._getId(root.schema)); + if (refPath !== baseId) { + var id = normalizeId(refPath); + var refVal = this._refs[id]; + if (typeof refVal == 'string') { + return resolveRecursive.call(this, root, refVal, p); + } else if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + root = refVal; + } else { + refVal = this._schemas[id]; + if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + if (id == normalizeId(ref)) return { schema: refVal, root: root, baseId: baseId }; + root = refVal; + } else { + return; + } + } + if (!root.schema) return; + baseId = getFullPath(this._getId(root.schema)); + } + return getJsonPointer.call(this, p, baseId, root.schema, root); +} -function createDebug(namespace) { +/* @this Ajv */ +function resolveRecursive(root, ref, parsedRef) { + /* jshint validthis: true */ + var res = resolveSchema.call(this, root, ref); + if (res) { + var schema = res.schema; + var baseId = res.baseId; + root = res.root; + var id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + return getJsonPointer.call(this, parsedRef, baseId, schema, root); + } +} - function debug() { - // disabled? - if (!debug.enabled) return; +var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); +/* @this Ajv */ +function getJsonPointer(parsedRef, baseId, schema, root) { + /* jshint validthis: true */ + parsedRef.hash = parsedRef.hash || ''; + if (parsedRef.hash.slice(0, 2) != '#/') return; + var parts = parsedRef.hash.split('/'); + + for (var i = 1; i < parts.length; i++) { + var part = parts[i]; + if (part) { + part = util.unescapeFragment(part); + schema = schema[part]; + if (schema === undefined) break; + var id; + if (!PREVENT_SCOPE_CHANGE[part]) { + id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + if (schema.$ref) { + var $ref = resolveUrl(baseId, schema.$ref); + var res = resolveSchema.call(this, root, $ref); + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } + } + } + } + } + if (schema !== undefined && schema !== root.schema) return { schema: schema, root: root, baseId: baseId }; +} - var self = debug; +var SIMPLE_INLINED = util.toHash(['type', 'format', 'pattern', 'maxLength', 'minLength', 'maxProperties', 'minProperties', 'maxItems', 'minItems', 'maximum', 'minimum', 'uniqueItems', 'multipleOf', 'required', 'enum']); +function inlineRef(schema, limit) { + if (limit === false) return false; + if (limit === undefined || limit === true) return checkNoRef(schema);else if (limit) return countKeys(schema) <= limit; +} - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +function checkNoRef(schema) { + var item; + if (Array.isArray(schema)) { + for (var i = 0; i < schema.length; i++) { + item = schema[i]; + if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) == 'object' && !checkNoRef(item)) return false; + } + } else { + for (var key in schema) { + if (key == '$ref') return false; + item = schema[key]; + if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) == 'object' && !checkNoRef(item)) return false; + } + } + return true; +} - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; +function countKeys(schema) { + var count = 0, + item; + if (Array.isArray(schema)) { + for (var i = 0; i < schema.length; i++) { + item = schema[i]; + if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) == 'object') count += countKeys(item); + if (count == Infinity) return Infinity; + } + } else { + for (var key in schema) { + if (key == '$ref') return Infinity; + if (SIMPLE_INLINED[key]) { + count++; + } else { + item = schema[key]; + if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) == 'object') count += countKeys(item) + 1; + if (count == Infinity) return Infinity; + } } + } + return count; +} - args[0] = exports.coerce(args[0]); +function getFullPath(id, normalize) { + if (normalize !== false) id = normalizeId(id); + var p = url.parse(id, false, true); + return _getFullPath(p); +} - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); +function _getFullPath(p) { + var protocolSeparator = p.protocol || p.href.slice(0, 2) == '//' ? '//' : ''; + return (p.protocol || '') + protocolSeparator + (p.host || '') + (p.path || '') + '#'; +} + +var TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; +} + +function resolveUrl(baseId, id) { + id = normalizeId(id); + return url.resolve(baseId, id); +} + +/* @this Ajv */ +function resolveIds(schema) { + var schemaId = normalizeId(this._getId(schema)); + var baseIds = { '': schemaId }; + var fullPaths = { '': getFullPath(schemaId, false) }; + var localRefs = {}; + var self = this; + + traverse(schema, { allKeys: true }, function (sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (jsonPtr === '') return; + var id = self._getId(sch); + var baseId = baseIds[parentJsonPtr]; + var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword; + if (keyIndex !== undefined) fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex)); + + if (typeof id == 'string') { + id = baseId = normalizeId(baseId ? url.resolve(baseId, id) : id); + + var refVal = self._refs[id]; + if (typeof refVal == 'string') refVal = self._refs[refVal]; + if (refVal && refVal.schema) { + if (!equal(sch, refVal.schema)) throw new Error('id "' + id + '" resolves to more than one schema'); + } else if (id != normalizeId(fullPath)) { + if (id[0] == '#') { + if (localRefs[id] && !equal(sch, localRefs[id])) throw new Error('id "' + id + '" resolves to more than one schema'); + localRefs[id] = sch; + } else { + self._refs[id] = fullPath; + } + } } + baseIds[jsonPtr] = baseId; + fullPaths[jsonPtr] = fullPath; + }); - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + return localRefs; +} - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; +},{"./schema_obj":16,"./util":18,"fast-deep-equal":78,"json-schema-traverse":84,"url":112}],15:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var ruleModules = require('./_rules'), + toHash = require('./util').toHash; + +module.exports = function rules() { + var RULES = [{ type: 'number', + rules: [{ 'maximum': ['exclusiveMaximum'] }, { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, { type: 'string', + rules: ['maxLength', 'minLength', 'pattern', 'format'] }, { type: 'array', + rules: ['maxItems', 'minItems', 'uniqueItems', 'contains', 'items'] }, { type: 'object', + rules: ['maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', { 'properties': ['additionalProperties', 'patternProperties'] }] }, { rules: ['$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf'] }]; + + var ALL = ['type']; + var KEYWORDS = ['additionalItems', '$schema', 'id', 'title', 'description', 'default', 'definitions']; + var TYPES = ['number', 'integer', 'string', 'array', 'object', 'boolean', 'null']; + RULES.all = toHash(ALL); + RULES.types = toHash(TYPES); + + RULES.forEach(function (group) { + group.rules = group.rules.map(function (keyword) { + var implKeywords; + if ((typeof keyword === 'undefined' ? 'undefined' : _typeof(keyword)) == 'object') { + var key = Object.keys(keyword)[0]; + implKeywords = keyword[key]; + keyword = key; + implKeywords.forEach(function (k) { + ALL.push(k); + RULES.all[k] = true; + }); } - return match; + ALL.push(keyword); + var rule = RULES.all[keyword] = { + keyword: keyword, + code: ruleModules[keyword], + implements: implKeywords + }; + return rule; }); - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + if (group.type) RULES.types[group.type] = group; + }); - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.custom = {}; - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); + return RULES; +}; - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +},{"./_rules":9,"./util":18}],16:[function(require,module,exports){ +'use strict'; - return debug; -} +var util = require('./util'); -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ +module.exports = SchemaObject; -function enable(namespaces) { - exports.save(namespaces); +function SchemaObject(obj) { + util.copy(obj, this); +} - exports.names = []; - exports.skips = []; +},{"./util":18}],17:[function(require,module,exports){ +'use strict'; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); +module.exports = function ucs2length(str) { + var length = 0, + len = str.length, + pos = 0, + value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate } } -} + return length; +}; -/** - * Disable debug output. - * - * @api public - */ +},{}],18:[function(require,module,exports){ +'use strict'; -function disable() { - exports.enable(''); +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: require('fast-deep-equal'), + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + cleanUpCode: cleanUpCode, + finalCleanUpCode: finalCleanUpCode, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + +function copy(o, to) { + to = to || {}; + for (var key in o) { + to[key] = o[key]; + }return to; } -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +function checkDataType(dataType, data, negate) { + var EQUAL = negate ? ' !== ' : ' === ', + AND = negate ? ' || ' : ' && ', + OK = negate ? '!' : '', + NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': + return data + EQUAL + 'null'; + case 'array': + return OK + 'Array.isArray(' + data + ')'; + case 'object': + return '(' + OK + data + AND + 'typeof ' + data + EQUAL + '"object"' + AND + NOT + 'Array.isArray(' + data + '))'; + case 'integer': + return '(typeof ' + data + EQUAL + '"number"' + AND + NOT + '(' + data + ' % 1)' + AND + data + EQUAL + data + ')'; + default: + return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } +function checkDataTypes(dataTypes, data) { + switch (dataTypes.length) { + case 1: + return checkDataType(dataTypes[0], data, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(' : '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) { + code += (code ? ' && ' : '') + checkDataType(t, data, true); + }return code; } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; +} + +var COERCE_TO_TYPES = toHash(['string', 'number', 'integer', 'boolean', 'null']); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i = 0; i < dataTypes.length; i++) { + var t = dataTypes[i]; + if (COERCE_TO_TYPES[t]) types[types.length] = t;else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t; } + if (types.length) return types; + } else if (COERCE_TO_TYPES[dataTypes]) { + return [dataTypes]; + } else if (optionCoerceTypes === 'array' && dataTypes === 'array') { + return ['array']; } - return false; } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function toHash(arr) { + var hash = {}; + for (var i = 0; i < arr.length; i++) { + hash[arr[i]] = true; + }return hash; } -},{"ms":114}],10:[function(require,module,exports){ -/* - * @fileoverview Main Doctrine object - * @author Yusuke Suzuki - * @author Dan Tao - * @author Andrew Eisenberg - */ - -(function () { - 'use strict'; - - var typed, - utility, - isArray, - jsdoc, - esutils, - hasOwnProperty; - - esutils = require('esutils'); - isArray = require('isarray'); - typed = require('./typed'); - utility = require('./utility'); +var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; +var SINGLE_QUOTE = /'|\\/g; +function getProperty(key) { + return typeof key == 'number' ? '[' + key + ']' : IDENTIFIER.test(key) ? '.' + key : "['" + escapeQuotes(key) + "']"; +} - function sliceSource(source, index, last) { - return source.slice(index, last); - } +function escapeQuotes(str) { + return str.replace(SINGLE_QUOTE, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\f/g, '\\f').replace(/\t/g, '\\t'); +} - hasOwnProperty = (function () { - var func = Object.prototype.hasOwnProperty; - return function hasOwnProperty(obj, name) { - return func.call(obj, name); - }; - }()); +function varOccurences(str, dataVar) { + dataVar += '[^0-9]'; + var matches = str.match(new RegExp(dataVar, 'g')); + return matches ? matches.length : 0; +} - function shallowCopy(obj) { - var ret = {}, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - ret[key] = obj[key]; - } - } - return ret; - } +function varReplace(str, dataVar, expr) { + dataVar += '([^0-9])'; + expr = expr.replace(/\$/g, '$$$$'); + return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); +} - function isASCIIAlphanumeric(ch) { - return (ch >= 0x61 /* 'a' */ && ch <= 0x7A /* 'z' */) || - (ch >= 0x41 /* 'A' */ && ch <= 0x5A /* 'Z' */) || - (ch >= 0x30 /* '0' */ && ch <= 0x39 /* '9' */); - } +var EMPTY_ELSE = /else\s*{\s*}/g, + EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g, + EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g; +function cleanUpCode(out) { + return out.replace(EMPTY_ELSE, '').replace(EMPTY_IF_NO_ELSE, '').replace(EMPTY_IF_WITH_ELSE, 'if (!($1))'); +} - function isParamTitle(title) { - return title === 'param' || title === 'argument' || title === 'arg'; - } +var ERRORS_REGEXP = /[^v.]errors/g, + REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g, + REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g, + RETURN_VALID = 'return errors === 0;', + RETURN_TRUE = 'validate.errors = null; return true;', + RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/, + RETURN_DATA_ASYNC = 'return data;', + ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g, + REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/; + +function finalCleanUpCode(out, async) { + var matches = out.match(ERRORS_REGEXP); + if (matches && matches.length == 2) { + out = async ? out.replace(REMOVE_ERRORS_ASYNC, '').replace(RETURN_ASYNC, RETURN_DATA_ASYNC) : out.replace(REMOVE_ERRORS, '').replace(RETURN_VALID, RETURN_TRUE); + } + + matches = out.match(ROOTDATA_REGEXP); + if (!matches || matches.length !== 3) return out; + return out.replace(REMOVE_ROOTDATA, ''); +} - function isReturnTitle(title) { - return title === 'return' || title === 'returns'; - } +function schemaHasRules(schema, rules) { + if (typeof schema == 'boolean') return !schema; + for (var key in schema) { + if (rules[key]) return true; + } +} - function isProperty(title) { - return title === 'property' || title === 'prop'; - } +function schemaHasRulesExcept(schema, rules, exceptKeyword) { + if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not'; + for (var key in schema) { + if (key != exceptKeyword && rules[key]) return true; + } +} - function isNameParameterRequired(title) { - return isParamTitle(title) || isProperty(title) || - title === 'alias' || title === 'this' || title === 'mixes' || title === 'requires'; - } +function toQuotedString(str) { + return '\'' + escapeQuotes(str) + '\''; +} - function isAllowedName(title) { - return isNameParameterRequired(title) || title === 'const' || title === 'constant'; - } +function getPathExpr(currentPath, expr, jsonPointers, isNumber) { + var path = jsonPointers // false by default + ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') : isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''; + return joinPaths(currentPath, path); +} - function isAllowedNested(title) { - return isProperty(title) || isParamTitle(title); - } +function getPath(currentPath, prop, jsonPointers) { + var path = jsonPointers // false by default + ? toQuotedString('/' + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop)); + return joinPaths(currentPath, path); +} - function isAllowedOptional(title) { - return isProperty(title) || isParamTitle(title); +var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; +var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; +function getData($data, lvl, paths) { + var up, jsonPointer, data, matches; + if ($data === '') return 'rootData'; + if ($data[0] == '/') { + if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); + jsonPointer = $data; + data = 'rootData'; + } else { + matches = $data.match(RELATIVE_JSON_POINTER); + if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); + up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer == '#') { + if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; } - function isTypeParameterRequired(title) { - return isParamTitle(title) || isReturnTitle(title) || - title === 'define' || title === 'enum' || - title === 'implements' || title === 'this' || - title === 'type' || title === 'typedef' || isProperty(title); - } + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + (lvl - up || ''); + if (!jsonPointer) return data; + } - // Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick when a type is optional/required - // This would require changes to 'parseType' - function isAllowedType(title) { - return isTypeParameterRequired(title) || title === 'throws' || title === 'const' || title === 'constant' || - title === 'namespace' || title === 'member' || title === 'var' || title === 'module' || - title === 'constructor' || title === 'class' || title === 'extends' || title === 'augments' || - title === 'public' || title === 'private' || title === 'protected'; + var expr = data; + var segments = jsonPointer.split('/'); + for (var i = 0; i < segments.length; i++) { + var segment = segments[i]; + if (segment) { + data += getProperty(unescapeJsonPointer(segment)); + expr += ' && ' + data; } + } + return expr; +} - function trim(str) { - return str.replace(/^\s+/, '').replace(/\s+$/, ''); - } +function joinPaths(a, b) { + if (a == '""') return b; + return (a + ' + ' + b).replace(/' \+ '/g, ''); +} - function unwrapComment(doc) { - // JSDoc comment is following form - // /** - // * ....... - // */ - // remove /**, */ and * - var BEFORE_STAR = 0, - STAR = 1, - AFTER_STAR = 2, - index, - len, - mode, - result, - ch; +function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); +} - doc = doc.replace(/^\/\*\*?/, '').replace(/\*\/$/, ''); - index = 0; - len = doc.length; - mode = BEFORE_STAR; - result = ''; +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); +} - while (index < len) { - ch = doc.charCodeAt(index); - switch (mode) { - case BEFORE_STAR: - if (esutils.code.isLineTerminator(ch)) { - result += String.fromCharCode(ch); - } else if (ch === 0x2A /* '*' */) { - mode = STAR; - } else if (!esutils.code.isWhiteSpace(ch)) { - result += String.fromCharCode(ch); - mode = AFTER_STAR; - } - break; +function escapeJsonPointer(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); +} - case STAR: - if (!esutils.code.isWhiteSpace(ch)) { - result += String.fromCharCode(ch); - } - mode = esutils.code.isLineTerminator(ch) ? BEFORE_STAR : AFTER_STAR; - break; +function unescapeJsonPointer(str) { + return str.replace(/~1/g, '/').replace(/~0/g, '~'); +} - case AFTER_STAR: - result += String.fromCharCode(ch); - if (esutils.code.isLineTerminator(ch)) { - mode = BEFORE_STAR; - } - break; - } - index += 1; - } +},{"./ucs2length":17,"fast-deep-equal":78}],19:[function(require,module,exports){ +'use strict'; - return result.replace(/\s+$/, ''); +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + $lvl + ' = ' + $schemaValueExcl + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + $exclusive + '; var ' + $exclType + ' = typeof ' + $schemaValueExcl + '; if (' + $exclType + ' != \'boolean\' && ' + $exclType + ' != \'undefined\' && ' + $exclType + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + $exclusiveKeyword + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; } - - // JSDoc Tag Parser - - (function (exports) { - var Rules, - index, - lineNumber, - length, - source, - recoverable, - sloppy, - strict; - - function advance() { - var ch = source.charCodeAt(index); - index += 1; - if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(index) === 0x0A /* '\n' */)) { - lineNumber += 1; - } - return String.fromCharCode(ch); + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } + out += ' ' + $exclType + ' == \'number\' ? ( (' + $exclusive + ' = ' + $schemaValue + ' === undefined || ' + $schemaValueExcl + ' ' + $op + '= ' + $schemaValue + ') ? ' + $data + ' ' + $notOp + '= ' + $schemaValueExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) : ( (' + $exclusive + ' = ' + $schemaValueExcl + ' === true) ? ' + $data + ' ' + $notOp + '= ' + $schemaValue + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { var op' + $lvl + ' = ' + $exclusive + ' ? \'' + $op + '\' : \'' + $op + '=\';'; + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } + out += ' ( ' + $schemaValue + ' === undefined || ' + $schemaExcl + ' ' + $op + '= ' + $schemaValue + ' ? ' + $data + ' ' + $notOp + '= ' + $schemaExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } + out += ' ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' || ' + $data + ' !== ' + $data + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { comparison: ' + $opExpr + ', limit: ' + $schemaValue + ', exclusive: ' + $exclusive + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + $opStr + ' '; + if ($isData) { + out += '\' + ' + $schemaValue; + } else { + out += '' + $schemaValue + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - function scanTitle() { - var title = ''; - // waste '@' - advance(); +},{}],20:[function(require,module,exports){ +'use strict'; - while (index < length && isASCIIAlphanumeric(source.charCodeAt(index))) { - title += advance(); - } +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } + out += ' ' + $data + '.length ' + $op + ' ' + $schemaValue + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'less'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + $schema; + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - return title; - } +},{}],21:[function(require,module,exports){ +'use strict'; - function seekContent() { - var ch, waiting, last = index; +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + $data + '.length '; + } else { + out += ' ucs2length(' + $data + ') '; + } + out += ' ' + $op + ' ' + $schemaValue + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + $schema; + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - waiting = false; - while (last < length) { - ch = source.charCodeAt(last); - if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(last + 1) === 0x0A /* '\n' */)) { - waiting = true; - } else if (waiting) { - if (ch === 0x40 /* '@' */) { - break; - } - if (!esutils.code.isWhiteSpace(ch)) { - waiting = false; - } - } - last += 1; - } - return last; - } +},{}],22:[function(require,module,exports){ +'use strict'; - // type expression may have nest brace, such as, - // { { ok: string } } - // - // therefore, scanning type expression with balancing braces. - function parseType(title, last) { - var ch, brace, type, direct = false; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || '; + } + out += ' Object.keys(' + $data + ').length ' + $op + ' ' + $schemaValue + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'less'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + $schema; + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; +},{}],23:[function(require,module,exports){ +'use strict'; - // search '{' - while (index < last) { - ch = source.charCodeAt(index); - if (esutils.code.isWhiteSpace(ch)) { - advance(); - } else if (ch === 0x7B /* '{' */) { - advance(); - break; - } else { - // this is direct pattern - direct = true; - break; - } - } +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + $closingBraces.slice(0, -1) + ' '; + } + } + out = it.util.cleanUpCode(out); + return out; +}; +},{}],24:[function(require,module,exports){ +'use strict'; - if (direct) { - return null; - } +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function ($sch) { + return it.util.schemaHasRules($sch, it.RULES.all); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + $errs + ' = errors; var ' + $valid + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + $valid + ' = ' + $valid + ' || ' + $nextValid + '; if (!' + $valid + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + $closingBraces + ' if (!' + $valid + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'anyOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +}; - // type expression { is found - brace = 1; - type = ''; - while (index < last) { - ch = source.charCodeAt(index); - if (esutils.code.isLineTerminator(ch)) { - advance(); - } else { - if (ch === 0x7D /* '}' */) { - brace -= 1; - if (brace === 0) { - advance(); - break; - } - } else if (ch === 0x7B /* '{' */) { - brace += 1; - } - type += advance(); - } - } +},{}],25:[function(require,module,exports){ +'use strict'; - if (brace !== 0) { - // braces is not balanced - return utility.throwError('Braces are not balanced'); - } +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + $lvl + ' = validate.schema' + $schemaPath + ';'; + } + out += 'var ' + $valid + ' = equal(' + $data + ', schema' + $lvl + '); if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'const' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - if (isAllowedOptional(title)) { - return typed.parseParamType(type); - } +},{}],26:[function(require,module,exports){ +'use strict'; - return typed.parseType(type); - } +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all); + out += 'var ' + $errs + ' = errors;var ' + $valid + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + $nextValid + ' = false; for (var ' + $idx + ' = 0; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + out += ' if (' + $nextValid + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + $closingBraces + ' if (!' + $nextValid + ') {'; + } else { + out += ' if (' + $data + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'contains' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + out = it.util.cleanUpCode(out); + return out; +}; - function scanIdentifier(last) { - var identifier; - if (!esutils.code.isIdentifierStartES5(source.charCodeAt(index))) { - return null; - } - identifier = advance(); - while (index < last && esutils.code.isIdentifierPartES5(source.charCodeAt(index))) { - identifier += advance(); - } - return identifier; - } +},{}],27:[function(require,module,exports){ +'use strict'; - function skipWhiteSpace(last) { - while (index < last && (esutils.code.isWhiteSpace(source.charCodeAt(index)) || esutils.code.isLineTerminator(source.charCodeAt(index)))) { - advance(); - } +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + $definition + ' = RULES.custom[\'' + $keyword + '\'].definition; var ' + $validateCode + ' = ' + $definition + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + $ruleErrs + ' = null;'; + } + out += 'var ' + $errs + ' = errors;var ' + $valid + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + $schemaValue + ' === undefined) { ' + $valid + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + $valid + ' = ' + $definition + '.validateSchema(' + $schemaValue + '); if (' + $valid + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + $ruleValidate.validate + ' '; + } else { + out += ' ' + $valid + ' = ' + $ruleValidate.validate + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + $code; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + $validateCode + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + $data + ' '; + } else { + out += ' , ' + $schemaValue + ' , ' + $data + ' , validate.schema' + it.schemaPath + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + it.errorPath; + } + var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + $parentData + ' , ' + $parentDataProperty + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + $valid + ' = '; + if ($asyncKeyword) { + out += '' + it.yieldAwait; + } + out += '' + def_callRuleValidate + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + $ruleErrs + ' = null; try { ' + $valid + ' = ' + it.yieldAwait + def_callRuleValidate + '; } catch (e) { ' + $valid + ' = false; if (e instanceof ValidationError) ' + $ruleErrs + ' = e.errors; else throw e; } '; + } else { + out += ' ' + $ruleErrs + ' = null; ' + $valid + ' = ' + def_callRuleValidate + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + $parentData + ') ' + $data + ' = ' + $parentData + '[' + $parentDataProperty + '];'; + } + out += '' + $closingBraces; + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + $nextValid; + } else { + out += '' + $valid; + } + } else { + out += ' ' + !$rDef.valid + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { keyword: \'' + $rule.keyword + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + $rule.keyword + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + $i + '=' + $errs + '; ' + $i + '= last) { - return null; - } +},{}],28:[function(require,module,exports){ +'use strict'; - if (allowBrackets && source.charCodeAt(index) === 0x5B /* '[' */) { - useBrackets = true; - name = advance(); +module.exports = function generate_dependencies(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $schemaDeps = {}, + $propertyDeps = {}, + $ownProperties = it.opts.ownProperties; + for ($property in $schema) { + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } + out += 'var ' + $errs + ' = errors;'; + var $currentErrorPath = it.errorPath; + out += 'var missing' + $lvl + ';'; + for (var $property in $propertyDeps) { + $deps = $propertyDeps[$property]; + if ($deps.length) { + out += ' if ( ' + $data + it.util.getProperty($property) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') '; + } + if ($breakOnError) { + out += ' && ( '; + var arr1 = $deps; + if (arr1) { + var $propertyKey, + $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $propertyKey = arr1[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + $useData + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } + out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) '; + } + } + out += ')) { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'dependencies' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + it.util.escapeQuotes($deps[0]); + } else { + out += 'properties ' + it.util.escapeQuotes($deps.join(", ")); } - - if (!esutils.code.isIdentifierStartES5(source.charCodeAt(index))) { - return null; + out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + out += ' ) { '; + var arr2 = $deps; + if (arr2) { + var $propertyKey, + i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $propertyKey = arr2[i2 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + $useData + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'dependencies' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + it.util.escapeQuotes($deps[0]); + } else { + out += 'properties ' + it.util.escapeQuotes($deps.join(", ")); + } + out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; + for (var $property in $schemaDeps) { + var $sch = $schemaDeps[$property]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + out += ' ' + $nextValid + ' = true; if ( ' + $data + it.util.getProperty($property) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +}; - name += scanIdentifier(last); +},{}],29:[function(require,module,exports){ +'use strict'; - if (allowNestedParams) { - if (source.charCodeAt(index) === 0x3A /* ':' */ && ( - name === 'module' || - name === 'external' || - name === 'event')) { - name += advance(); - name += scanIdentifier(last); +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + ';'; + } + out += 'var ' + $valid + ';'; + if ($isData) { + out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {'; + } + out += '' + $valid + ' = false;for (var ' + $i + '=0; ' + $i + '<' + $vSchema + '.length; ' + $i + '++) if (equal(' + $data + ', ' + $vSchema + '[' + $i + '])) { ' + $valid + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'enum' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { allowedValues: schema' + $lvl + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - } - if(source.charCodeAt(index) === 0x5B /* '[' */ && source.charCodeAt(index + 1) === 0x5D /* ']' */){ - name += advance(); - name += advance(); - } - while (source.charCodeAt(index) === 0x2E /* '.' */ || - source.charCodeAt(index) === 0x2F /* '/' */ || - source.charCodeAt(index) === 0x23 /* '#' */ || - source.charCodeAt(index) === 0x2D /* '-' */ || - source.charCodeAt(index) === 0x7E /* '~' */) { - name += advance(); - name += scanIdentifier(last); - } - } +},{}],30:[function(require,module,exports){ +'use strict'; - if (useBrackets) { - skipWhiteSpace(last); - // do we have a default value for this? - if (source.charCodeAt(index) === 0x3D /* '=' */) { - // consume the '='' symbol - name += advance(); - skipWhiteSpace(last); +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - var ch; - var bracketDepth = 1; +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + $format + ' = formats[' + $schemaValue + ']; var ' + $isObject + ' = typeof ' + $format + ' == \'object\' && !(' + $format + ' instanceof RegExp) && ' + $format + '.validate; var ' + $formatType + ' = ' + $isObject + ' && ' + $format + '.type || \'string\'; if (' + $isObject + ') { '; + if (it.async) { + out += ' var async' + $lvl + ' = ' + $format + '.async; '; + } + out += ' ' + $format + ' = ' + $format + '.validate; } if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + $schemaValue + ' && !' + $format + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + $schemaValue + ') == -1 '; + } + out += ') || '; + } + out += ' (' + $format + ' && ' + $formatType + ' == \'' + $ruleType + '\' && !(typeof ' + $format + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + $lvl + ' ? ' + it.yieldAwait + ' ' + $format + '(' + $data + ') : ' + $format + '(' + $data + ')) '; + } else { + out += ' ' + $format + '(' + $data + ') '; + } + out += ' : ' + $format + '.test(' + $data + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = (typeof $format === 'undefined' ? 'undefined' : _typeof($format)) == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(' + it.yieldAwait + ' ' + $formatRef + '(' + $data + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + $formatRef + '(' + $data + ') '; + } else { + out += ' ' + $formatRef + '.test(' + $data + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'format' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { format: '; + if ($isData) { + out += '' + $schemaValue; + } else { + out += '' + it.util.toQuotedString($schema); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + it.util.escapeQuotes($schema); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + it.util.toQuotedString($schema); + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - // scan in the default value - while (index < last) { - ch = source.charCodeAt(index); +},{}],31:[function(require,module,exports){ +'use strict'; - if (esutils.code.isWhiteSpace(ch)) { - if (!insideString) { - skipWhiteSpace(last); - ch = source.charCodeAt(index); - } - } +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - if (ch === 0x27 /* ''' */) { - if (!insideString) { - insideString = '\''; - } else { - if (insideString === '\'') { - insideString = ''; - } - } - } +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + $errs + ' = errors;var ' + $valid + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + $valid + ' = ' + $data + '.length <= ' + $schema.length + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'additionalItems' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schema.length + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + $schema.length + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $i + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } + } + if ((typeof $additionalItems === 'undefined' ? 'undefined' : _typeof($additionalItems)) == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $schema.length + ') { for (var ' + $idx + ' = ' + $schema.length + '; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } else if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + $idx + ' = ' + 0 + '; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +}; - if (ch === 0x22 /* '"' */) { - if (!insideString) { - insideString = '"'; - } else { - if (insideString === '"') { - insideString = ''; - } - } - } +},{}],32:[function(require,module,exports){ +'use strict'; - if (ch === 0x5B /* '[' */) { - bracketDepth++; - } else if (ch === 0x5D /* ']' */ && - --bracketDepth === 0) { - break; - } +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + out += 'var division' + $lvl + ';if ('; + if ($isData) { + out += ' ' + $schemaValue + ' !== undefined && ( typeof ' + $schemaValue + ' != \'number\' || '; + } + out += ' (division' + $lvl + ' = ' + $data + ' / ' + $schemaValue + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + $lvl + ') - division' + $lvl + ') > 1e-' + it.opts.multipleOfPrecision + ' '; + } else { + out += ' division' + $lvl + ' !== parseInt(division' + $lvl + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'multipleOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { multipleOf: ' + $schemaValue + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + $schemaValue; + } else { + out += '' + $schemaValue + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - name += advance(); - } - } +},{}],33:[function(require,module,exports){ +'use strict'; - skipWhiteSpace(last); +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + $errs + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + it.validate($it) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + $nextValid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'not' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'not' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +}; - if (index >= last || source.charCodeAt(index) !== 0x5D /* ']' */) { - // we never found a closing ']' - return null; - } +},{}],34:[function(require,module,exports){ +'use strict'; - // collect the last ']' - name += advance(); - } +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + $errs + ' = errors;var prevValid' + $lvl + ' = false;var ' + $valid + ' = false;'; + var $currentBaseId = $it.baseId; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, + $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + it.validate($it) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + $nextValid + ' = true; '; + } + if ($i) { + out += ' if (' + $nextValid + ' && prevValid' + $lvl + ') ' + $valid + ' = false; else { '; + $closingBraces += '}'; + } + out += ' if (' + $nextValid + ') ' + $valid + ' = prevValid' + $lvl + ' = true;'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + $closingBraces + 'if (!' + $valid + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'oneOf' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +}; - return name; - } +},{}],35:[function(require,module,exports){ +'use strict'; - function skipToTag() { - while (index < length && source.charCodeAt(index) !== 0x40 /* '@' */) { - advance(); - } - if (index >= length) { - return false; - } - utility.assert(source.charCodeAt(index) === 0x40 /* '@' */); - return true; - } +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || '; + } + out += ' !' + $regexp + '.test(' + $data + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'pattern' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { pattern: '; + if ($isData) { + out += '' + $schemaValue; + } else { + out += '' + it.util.toQuotedString($schema); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + $schemaValue + ' + \''; + } else { + out += '' + it.util.escapeQuotes($schema); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + it.util.toQuotedString($schema); + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +}; - function TagParser(options, title) { - this._options = options; - this._title = title.toLowerCase(); - this._tag = { - title: title, - description: null - }; - if (this._options.lineNumbers) { - this._tag.lineNumber = lineNumber; - } - this._last = 0; - // space to save special information for title parsers. - this._extra = { }; - } +},{}],36:[function(require,module,exports){ +'use strict'; - // addError(err, ...) - TagParser.prototype.addError = function addError(errorText) { - var args = Array.prototype.slice.call(arguments, 1), - msg = errorText.replace( - /%(\d)/g, - function (whole, index) { - utility.assert(index < args.length, 'Message reference must be in range'); - return args[index]; - } - ); +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - if (!this._tag.errors) { - this._tag.errors = []; +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = (typeof $aProperties === 'undefined' ? 'undefined' : _typeof($aProperties)) == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); + if (it.opts.patternGroups) { + var $pgProperties = it.schema.patternGroups || {}, + $pgPropertyKeys = Object.keys($pgProperties); + } + out += 'var ' + $errs + ' = errors;var ' + $nextValid + ' = true;'; + if ($ownProperties) { + out += ' var ' + $dataProperties + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; '; + } else { + out += ' for (var ' + $key + ' in ' + $data + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + $lvl + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 5) { + out += ' || validate.schema' + $schemaPath + '[' + $key + '] '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, + i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + $key + ' == ' + it.util.toQuotedString($propertyKey) + ' '; } - if (strict) { - utility.throwError(msg); + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, + $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + it.usePattern($pProperty) + '.test(' + $key + ') '; + } + } + } + if (it.opts.patternGroups && $pgPropertyKeys.length) { + var arr3 = $pgPropertyKeys; + if (arr3) { + var $pgProperty, + $i = -1, + l3 = arr3.length - 1; + while ($i < l3) { + $pgProperty = arr3[$i += 1]; + out += ' || ' + it.usePattern($pgProperty) + '.test(' + $key + ') '; + } + } + } + out += ' ); if (isAdditional' + $lvl + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + $data + '[' + $key + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + $data + '[' + $key + ']; '; + } else { + out += ' ' + $nextValid + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'additionalProperties' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { additionalProperty: \'' + $additionalProperty + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have additional properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; } - this._tag.errors.push(msg); - return recoverable; - }; - - TagParser.prototype.parseType = function () { - // type required titles - if (isTypeParameterRequired(this._title)) { - try { - this._tag.type = parseType(this._title, this._last); - if (!this._tag.type) { - if (!isParamTitle(this._title) && !isReturnTitle(this._title)) { - if (!this.addError('Missing or invalid tag type')) { - return false; - } - } - } - } catch (error) { - this._tag.type = null; - if (!this.addError(error.message)) { - return false; - } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + $errs + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + out += ' if (!' + $nextValid + ') { errors = ' + $errs + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + $data + '[' + $key + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr4 = $schemaKeys; + if (arr4) { + var $propertyKey, + i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $propertyKey = arr4[i4 += 1]; + var $sch = $schema[$propertyKey]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + $nextData + ' = ' + $passData + '; '; + } + if ($hasDefault) { + out += ' ' + $code + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + $useData + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } + out += ') { ' + $nextValid + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } + out += '\' '; } - } else if (isAllowedType(this._title)) { - // optional types - try { - this._tag.type = parseType(this._title, this._last); - } catch (e) { - //For optional types, lets drop the thrown error when we hit the end of the file + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + $useData + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } + out += ') { ' + $nextValid + ' = true; } else { '; + } else { + out += ' if (' + $useData + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; } + out += ' ) { '; + } } - return true; - }; - - TagParser.prototype._parseNamePath = function (optional) { - var name; - name = parseName(this._last, sloppy && isAllowedOptional(this._title), true); - if (!name) { - if (!optional) { - if (!this.addError('Missing or invalid tag name')) { - return false; - } + out += ' ' + $code + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($pPropertyKeys.length) { + var arr5 = $pPropertyKeys; + if (arr5) { + var $pProperty, + i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $pProperty = arr5[i5 += 1]; + var $sch = $pProperties[$pProperty]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; '; + } else { + out += ' for (var ' + $key + ' in ' + $data + ') { '; + } + out += ' if (' + it.usePattern($pProperty) + '.test(' + $key + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + $nextValid + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + } + } + } + } + if (it.opts.patternGroups && $pgPropertyKeys.length) { + var arr6 = $pgPropertyKeys; + if (arr6) { + var $pgProperty, + i6 = -1, + l6 = arr6.length - 1; + while (i6 < l6) { + $pgProperty = arr6[i6 += 1]; + var $pgSchema = $pgProperties[$pgProperty], + $sch = $pgSchema.schema; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema'; + $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema'; + out += ' var pgPropCount' + $lvl + ' = 0; '; + if ($ownProperties) { + out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; '; + } else { + out += ' for (var ' + $key + ' in ' + $data + ') { '; + } + out += ' if (' + it.usePattern($pgProperty) + '.test(' + $key + ')) { pgPropCount' + $lvl + '++; '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + if ($breakOnError) { + out += ' if (!' + $nextValid + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + $nextValid + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + $nextValid + ') { '; + $closingBraces += '}'; + } + var $pgMin = $pgSchema.minimum, + $pgMax = $pgSchema.maximum; + if ($pgMin !== undefined || $pgMax !== undefined) { + out += ' var ' + $valid + ' = true; '; + var $currErrSchemaPath = $errSchemaPath; + if ($pgMin !== undefined) { + var $limit = $pgMin, + $reason = 'minimum', + $moreOrLess = 'less'; + out += ' ' + $valid + ' = pgPropCount' + $lvl + ' >= ' + $pgMin + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum'; + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'patternGroups' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { reason: \'' + $reason + '\', limit: ' + $limit + ', pattern: \'' + it.util.escapeQuotes($pgProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + $moreOrLess + ' than ' + $limit + ' properties matching pattern "' + it.util.escapeQuotes($pgProperty) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($pgMax !== undefined) { + out += ' else '; + } } - this._tag.name = name; - return true; - }; + if ($pgMax !== undefined) { + var $limit = $pgMax, + $reason = 'maximum', + $moreOrLess = 'more'; + out += ' ' + $valid + ' = pgPropCount' + $lvl + ' <= ' + $pgMax + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum'; + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'patternGroups' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { reason: \'' + $reason + '\', limit: ' + $limit + ', pattern: \'' + it.util.escapeQuotes($pgProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + $moreOrLess + ' than ' + $limit + ' properties matching pattern "' + it.util.escapeQuotes($pgProperty) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' if (' + $valid + ') { '; + $closingBraces += '}'; + } + } + } + } + } + } + if ($breakOnError) { + out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +}; - TagParser.prototype.parseNamePath = function () { - return this._parseNamePath(false); - }; +},{}],37:[function(require,module,exports){ +'use strict'; - TagParser.prototype.parseNamePathOptional = function () { - return this._parseNamePath(true); - }; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + out += ' var ' + $errs + ' = errors; '; + if ($ownProperties) { + out += ' var ' + $dataProperties + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; '; + } else { + out += ' for (var ' + $key + ' in ' + $data + ') { '; + } + out += ' var startErrs' + $lvl + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' '; + } else { + out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + $nextValid + ') { for (var ' + $i + '=startErrs' + $lvl + '; ' + $i + '= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + $lvl + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + $valid + ' = true; '; + if ($isData) { + out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {'; + } + out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { ' + $valid + ' = ' + $data + '[' + $vSchema + '[' + $i + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) '; + } + out += '; if (!' + $valid + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, + $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + $useData + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } + out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + $vSchema + ' && !Array.isArray(' + $vSchema + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + $vSchema + ' !== undefined) { '; + } + out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { if (' + $data + '[' + $vSchema + '[' + $i + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + $missingProperty + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, + i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + $useData + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'required' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; } else { - name = this._tag.name; - if (name.charAt(0) === '[' && name.charAt(name.length - 1) === ']') { - // extract the default value if there is one - // example: @param {string} [somebody=John Doe] description - assign = name.substring(1, name.length - 1).split('='); - if (assign[1]) { - this._tag['default'] = assign[1]; - } - this._tag.name = assign[0]; - - // convert to an optional type - if (this._tag.type && this._tag.type.type !== 'OptionalType') { - this._tag.type = { - type: 'OptionalType', - expression: this._tag.type - }; - } - } + out += 'should have required property \\\'' + $missingProperty + '\\\''; } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +}; +},{}],40:[function(require,module,exports){ +'use strict'; - return true; - }; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + $valid + '; if (' + $schemaValue + ' === false || ' + $schemaValue + ' === undefined) ' + $valid + ' = true; else if (typeof ' + $schemaValue + ' != \'boolean\') ' + $valid + ' = false; else { '; + } + out += ' var ' + $valid + ' = true; if (' + $data + '.length > 1) { var i = ' + $data + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + $data + '[i], ' + $data + '[j])) { ' + $valid + ' = false; break outer; } } } } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + $valid + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + 'uniqueItems' + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + $schemaPath; + } else { + out += '' + $schema; + } + out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +}; - TagParser.prototype.parseDescription = function parseDescription() { - var description = trim(sliceSource(source, index, this._last)); - if (description) { - if ((/^-\s+/).test(description)) { - description = description.substring(2); - } - this._tag.description = description; - } - return true; - }; +},{}],41:[function(require,module,exports){ +'use strict'; - TagParser.prototype.parseCaption = function parseDescription() { - var description = trim(sliceSource(source, index, this._last)); - var captionStartTag = ''; - var captionEndTag = ''; - var captionStart = description.indexOf(captionStartTag); - var captionEnd = description.indexOf(captionEndTag); - if (captionStart >= 0 && captionEnd >= 0) { - this._tag.caption = trim(description.substring( - captionStart + captionStartTag.length, captionEnd)); - this._tag.description = trim(description.substring(captionEnd + captionEndTag.length)); +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.isTop) { + if ($async) { + it.async = true; + var $es7 = it.opts.async == 'es7'; + it.yieldAwait = $es7 ? 'await' : 'yield'; + } + out += ' var validate = '; + if ($async) { + if ($es7) { + out += ' (async function '; + } else { + if (it.opts.async != '*') { + out += 'co.wrap'; + } + out += '(function* '; + } + } else { + out += ' (function '; + } + out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + $valid + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + $valid + ' = true; '; + } + } + if (it.isTop) { + out += ' }); return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [undefined]; + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + $lvl + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + console.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + it.util[$method]($typeSchema, $data, true) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + $dataType + ' = typeof ' + $data + '; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + $dataType + ' == \'object\' && Array.isArray(' + $data + ')) ' + $dataType + ' = \'array\'; '; + } + out += ' var ' + $coerced + ' = undefined; '; + var $bracesCoercion = ''; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, + $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($i) { + out += ' if (' + $coerced + ' === undefined) { '; + $bracesCoercion += '}'; + } + if (it.opts.coerceTypes == 'array' && $type != 'array') { + out += ' if (' + $dataType + ' == \'array\' && ' + $data + '.length == 1) { ' + $coerced + ' = ' + $data + ' = ' + $data + '[0]; ' + $dataType + ' = typeof ' + $data + '; } '; + } + if ($type == 'string') { + out += ' if (' + $dataType + ' == \'number\' || ' + $dataType + ' == \'boolean\') ' + $coerced + ' = \'\' + ' + $data + '; else if (' + $data + ' === null) ' + $coerced + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' if (' + $dataType + ' == \'boolean\' || ' + $data + ' === null || (' + $dataType + ' == \'string\' && ' + $data + ' && ' + $data + ' == +' + $data + ' '; + if ($type == 'integer') { + out += ' && !(' + $data + ' % 1)'; + } + out += ')) ' + $coerced + ' = +' + $data + '; '; + } else if ($type == 'boolean') { + out += ' if (' + $data + ' === \'false\' || ' + $data + ' === 0 || ' + $data + ' === null) ' + $coerced + ' = false; else if (' + $data + ' === \'true\' || ' + $data + ' === 1) ' + $coerced + ' = true; '; + } else if ($type == 'null') { + out += ' if (' + $data + ' === \'\' || ' + $data + ' === 0 || ' + $data + ' === false) ' + $coerced + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' if (' + $dataType + ' == \'string\' || ' + $dataType + ' == \'number\' || ' + $dataType + ' == \'boolean\' || ' + $data + ' == null) ' + $coerced + ' = [' + $data + ']; '; + } + } + } + out += ' ' + $bracesCoercion + ' if (' + $coerced + ' === undefined) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + $typeSchema.join(","); } else { - this._tag.description = description; + out += '' + $typeSchema; } - return true; - }; - - TagParser.prototype.parseKind = function parseKind() { - var kind, kinds; - kinds = { - 'class': true, - 'constant': true, - 'event': true, - 'external': true, - 'file': true, - 'function': true, - 'member': true, - 'mixin': true, - 'module': true, - 'namespace': true, - 'typedef': true - }; - kind = trim(sliceSource(source, index, this._last)); - this._tag.kind = kind; - if (!hasOwnProperty(kinds, kind)) { - if (!this.addError('Invalid kind name \'%0\'', kind)) { - return false; + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + $data + ' = ' + $coerced + '; '; + if (!$dataLvl) { + out += 'if (' + $parentData + ' !== undefined)'; + } + out += ' ' + $parentData + '[' + $parentDataProperty + '] = ' + $coerced + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; + } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' } '; + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + it.RULES.all.$ref.code(it, '$ref') + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + $lvl; + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + if (it.opts.v5 && it.schema.patternGroups) { + console.warn('keyword "patternGroups" is deprecated and disabled. Use option patternGroups: true to enable.'); + } + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, + i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + it.util.checkDataType($rulesGroup.type, $data) + ') { '; + } + if (it.opts.useDefaults && !it.compositeRule) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, + i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + out += ' if (' + $passData + ' === undefined) ' + $passData + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + it.useDefault($sch.default) + ' '; + } else { + out += ' ' + JSON.stringify($sch.default) + ' '; + } + out += '; '; + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, + $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + out += ' if (' + $passData + ' === undefined) ' + $passData + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + it.useDefault($sch.default) + ' '; + } else { + out += ' ' + JSON.stringify($sch.default) + ' '; + } + out += '; '; + } } + } } - return true; - }; - - TagParser.prototype.parseAccess = function parseAccess() { - var access; - access = trim(sliceSource(source, index, this._last)); - this._tag.access = access; - if (access !== 'private' && access !== 'protected' && access !== 'public') { - if (!this.addError('Invalid access name \'%0\'', access)) { - return false; + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, + i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + $code + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } } + } } - return true; - }; - - TagParser.prototype.parseThis = function parseAccess() { - // this name may be a name expression (e.g. {foo.bar}) - // or a name path (e.g. foo.bar) - var value = trim(sliceSource(source, index, this._last)); - if (value && value.charAt(0) === '{') { - var gotType = this.parseType(); - if (gotType && this._tag.type.type === 'NameExpression') { - this._tag.name = this._tag.type.name; - return true; + } + if ($breakOnError) { + out += ' ' + $closingBraces1 + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + $typeSchema.join(","); } else { - return this.addError('Invalid name for this'); + out += '' + $typeSchema; + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + $typeSchema.join(","); + } else { + out += '' + $typeSchema; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + __err + ']); '; + } else { + out += ' validate.errors = [' + __err + ']; return false; '; } + } else { + out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; } else { - return this.parseNamePath(); + out += 'errs_' + $lvl; } - }; + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + $closingBraces2 + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }); return validate;'; + } else { + out += ' var ' + $valid + ' = errors === errs_' + $lvl + ';'; + } + out = it.util.cleanUpCode(out); + if ($top) { + out = it.util.finalCleanUpCode(out, $async); + } - TagParser.prototype.parseVariation = function parseVariation() { - var variation, text; - text = trim(sliceSource(source, index, this._last)); - variation = parseFloat(text, 10); - this._tag.variation = variation; - if (isNaN(variation)) { - if (!this.addError('Invalid variation \'%0\'', text)) { - return false; - } - } - return true; - }; - - TagParser.prototype.ensureEnd = function () { - var shouldBeEmpty = trim(sliceSource(source, index, this._last)); - if (shouldBeEmpty) { - if (!this.addError('Unknown content \'%0\'', shouldBeEmpty)) { - return false; - } - } - return true; - }; + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) { + if ($shouldUseRule(rules[i])) return true; + } + } - TagParser.prototype.epilogue = function epilogue() { - var description; + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || $rule.implements && $ruleImlementsSomeKeyword($rule); + } - description = this._tag.description; - // un-fix potentially sloppy declaration - if (isAllowedOptional(this._title) && !this._tag.type && description && description.charAt(0) === '[') { - this._tag.type = this._extra.name; - if (!this._tag.name) { - this._tag.name = undefined; - } + function $ruleImlementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) { + if (it.schema[impl[i]] !== undefined) return true; + } + } + return out; +}; - if (!sloppy) { - if (!this.addError('Missing or invalid tag name')) { - return false; - } - } - } +},{}],42:[function(require,module,exports){ +'use strict'; - return true; - }; +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = require('./dotjs/custom'); - Rules = { - // http://usejsdoc.org/tags-access.html - 'access': ['parseAccess'], - // http://usejsdoc.org/tags-alias.html - 'alias': ['parseNamePath', 'ensureEnd'], - // http://usejsdoc.org/tags-augments.html - 'augments': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // http://usejsdoc.org/tags-constructor.html - 'constructor': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // Synonym: http://usejsdoc.org/tags-constructor.html - 'class': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // Synonym: http://usejsdoc.org/tags-extends.html - 'extends': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // http://usejsdoc.org/tags-example.html - 'example': ['parseCaption'], - // http://usejsdoc.org/tags-deprecated.html - 'deprecated': ['parseDescription'], - // http://usejsdoc.org/tags-global.html - 'global': ['ensureEnd'], - // http://usejsdoc.org/tags-inner.html - 'inner': ['ensureEnd'], - // http://usejsdoc.org/tags-instance.html - 'instance': ['ensureEnd'], - // http://usejsdoc.org/tags-kind.html - 'kind': ['parseKind'], - // http://usejsdoc.org/tags-mixes.html - 'mixes': ['parseNamePath', 'ensureEnd'], - // http://usejsdoc.org/tags-mixin.html - 'mixin': ['parseNamePathOptional', 'ensureEnd'], - // http://usejsdoc.org/tags-member.html - 'member': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // http://usejsdoc.org/tags-method.html - 'method': ['parseNamePathOptional', 'ensureEnd'], - // http://usejsdoc.org/tags-module.html - 'module': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // Synonym: http://usejsdoc.org/tags-method.html - 'func': ['parseNamePathOptional', 'ensureEnd'], - // Synonym: http://usejsdoc.org/tags-method.html - 'function': ['parseNamePathOptional', 'ensureEnd'], - // Synonym: http://usejsdoc.org/tags-member.html - 'var': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // http://usejsdoc.org/tags-name.html - 'name': ['parseNamePath', 'ensureEnd'], - // http://usejsdoc.org/tags-namespace.html - 'namespace': ['parseType', 'parseNamePathOptional', 'ensureEnd'], - // http://usejsdoc.org/tags-private.html - 'private': ['parseType', 'parseDescription'], - // http://usejsdoc.org/tags-protected.html - 'protected': ['parseType', 'parseDescription'], - // http://usejsdoc.org/tags-public.html - 'public': ['parseType', 'parseDescription'], - // http://usejsdoc.org/tags-readonly.html - 'readonly': ['ensureEnd'], - // http://usejsdoc.org/tags-requires.html - 'requires': ['parseNamePath', 'ensureEnd'], - // http://usejsdoc.org/tags-since.html - 'since': ['parseDescription'], - // http://usejsdoc.org/tags-static.html - 'static': ['ensureEnd'], - // http://usejsdoc.org/tags-summary.html - 'summary': ['parseDescription'], - // http://usejsdoc.org/tags-this.html - 'this': ['parseThis', 'ensureEnd'], - // http://usejsdoc.org/tags-todo.html - 'todo': ['parseDescription'], - // http://usejsdoc.org/tags-typedef.html - 'typedef': ['parseType', 'parseNamePathOptional'], - // http://usejsdoc.org/tags-variation.html - 'variation': ['parseVariation'], - // http://usejsdoc.org/tags-version.html - 'version': ['parseDescription'] - }; +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword +}; - TagParser.prototype.parse = function parse() { - var i, iz, sequences, method; +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined'); - // empty title - if (!this._title) { - if (!this.addError('Missing or invalid title')) { - return null; - } - } + if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier'); - // Seek to content last index. - this._last = seekContent(this._title); + if (definition) { + if (definition.macro && definition.valid !== undefined) throw new Error('"valid" option cannot be used with macro keywords'); - if (hasOwnProperty(Rules, this._title)) { - sequences = Rules[this._title]; - } else { - // default sequences - sequences = ['parseType', 'parseName', 'parseDescription', 'epilogue']; - } + var dataType = definition.type; + if (Array.isArray(dataType)) { + var i, + len = dataType.length; + for (i = 0; i < len; i++) { + checkDataType(dataType[i]); + }for (i = 0; i < len; i++) { + _addRule(keyword, dataType[i], definition); + } + } else { + if (dataType) checkDataType(dataType); + _addRule(keyword, dataType, definition); + } - for (i = 0, iz = sequences.length; i < iz; ++i) { - method = sequences[i]; - if (!this[method]()) { - return null; - } - } + var $data = definition.$data === true && this._opts.$data; + if ($data && !definition.validate) throw new Error('$data support: "validate" function is not defined'); - return this._tag; + var metaSchema = definition.metaSchema; + if (metaSchema) { + if ($data) { + metaSchema = { + anyOf: [metaSchema, { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }] }; + } + definition.validateSchema = this.compile(metaSchema, true); + } + } - function parseTag(options) { - var title, parser, tag; - - // skip to tag - if (!skipToTag()) { - return null; - } + RULES.keywords[keyword] = RULES.all[keyword] = true; - // scan title - title = scanTitle(); + function _addRule(keyword, dataType, definition) { + var ruleGroup; + for (var i = 0; i < RULES.length; i++) { + var rg = RULES[i]; + if (rg.type == dataType) { + ruleGroup = rg; + break; + } + } - // construct tag parser - parser = new TagParser(options, title); - tag = parser.parse(); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.push(ruleGroup); + } - // Seek global index to end of this tag. - while (index < parser._last) { - advance(); - } + var rule = { + keyword: keyword, + definition: definition, + custom: true, + code: customRuleCode, + implements: definition.implements + }; + ruleGroup.rules.push(rule); + RULES.custom[keyword] = rule; + } - return tag; - } + function checkDataType(dataType) { + if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType); + } +} - // - // Parse JSDoc - // +/** + * Get keyword + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. + */ +function getKeyword(keyword) { + /* jshint validthis: true */ + var rule = this.RULES.custom[keyword]; + return rule ? rule.definition : this.RULES.keywords[keyword] || false; +} - function scanJSDocDescription(preserveWhitespace) { - var description = '', ch, atAllowed; +/** + * Remove keyword + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + */ +function removeKeyword(keyword) { + /* jshint validthis: true */ + var RULES = this.RULES; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + delete RULES.custom[keyword]; + for (var i = 0; i < RULES.length; i++) { + var rules = RULES[i].rules; + for (var j = 0; j < rules.length; j++) { + if (rules[j].keyword == keyword) { + rules.splice(j, 1); + break; + } + } + } +} - atAllowed = true; - while (index < length) { - ch = source.charCodeAt(index); +},{"./dotjs/custom":27}],43:[function(require,module,exports){ +'use strict'; - if (atAllowed && ch === 0x40 /* '@' */) { - break; - } +var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema'; - if (esutils.code.isLineTerminator(ch)) { - atAllowed = true; - } else if (atAllowed && !esutils.code.isWhiteSpace(ch)) { - atAllowed = false; - } +module.exports = function (ajv) { + var defaultMeta = ajv._opts.defaultMeta; + var metaSchemaRef = typeof defaultMeta == 'string' ? { $ref: defaultMeta } : ajv.getSchema(META_SCHEMA_ID) ? { $ref: META_SCHEMA_ID } : {}; - description += advance(); - } + ajv.addKeyword('patternGroups', { + // implemented in properties.jst + metaSchema: { + type: 'object', + additionalProperties: { + type: 'object', + required: ['schema'], + properties: { + maximum: { + type: 'integer', + minimum: 0 + }, + minimum: { + type: 'integer', + minimum: 0 + }, + schema: metaSchemaRef + }, + additionalProperties: false + } + } + }); + ajv.RULES.all.properties.implements.push('patternGroups'); +}; - return preserveWhitespace ? description : trim(description); +},{}],44:[function(require,module,exports){ +module.exports={ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#", + "description": "Meta-schema for $data reference (JSON-schema extension proposal)", + "type": "object", + "required": [ "$data" ], + "properties": { + "$data": { + "type": "string", + "anyOf": [ + { "format": "relative-json-pointer" }, + { "format": "json-pointer" } + ] } + }, + "additionalProperties": false +} - function parse(comment, options) { - var tags = [], tag, description, interestingTags, i, iz; - - if (options === undefined) { - options = {}; - } - - if (typeof options.unwrap === 'boolean' && options.unwrap) { - source = unwrapComment(comment); - } else { - source = comment; +},{}],45:[function(require,module,exports){ +module.exports={ + "id": "http://json-schema.org/draft-04/schema#", + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "positiveInteger": { + "type": "integer", + "minimum": 0 + }, + "positiveIntegerDefault0": { + "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ] + }, + "simpleTypes": { + "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "minItems": 1, + "uniqueItems": true + } + }, + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uri" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "boolean", + "default": false + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "boolean", + "default": false + }, + "maxLength": { "$ref": "#/definitions/positiveInteger" }, + "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/positiveInteger" }, + "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxProperties": { "$ref": "#/definitions/positiveInteger" }, + "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] } - - // array of relevant tags - if (options.tags) { - if (isArray(options.tags)) { - interestingTags = { }; - for (i = 0, iz = options.tags.length; i < iz; i++) { - if (typeof options.tags[i] === 'string') { - interestingTags[options.tags[i]] = true; - } else { - utility.throwError('Invalid "tags" parameter: ' + options.tags); - } - } - } else { - utility.throwError('Invalid "tags" parameter: ' + options.tags); + }, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true } - } - - length = source.length; - index = 0; - lineNumber = 0; - recoverable = options.recoverable; - sloppy = options.sloppy; - strict = options.strict; - - description = scanJSDocDescription(options.preserveWhitespace); + ] + }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "dependencies": { + "exclusiveMaximum": [ "maximum" ], + "exclusiveMinimum": [ "minimum" ] + }, + "default": {} +} - while (true) { - tag = parseTag(options); - if (!tag) { - break; - } - if (!interestingTags || interestingTags.hasOwnProperty(tag.title)) { - tags.push(tag); - } +},{}],46:[function(require,module,exports){ +module.exports={ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] } + }, + "propertyNames": { "$ref": "#" }, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": {} +} - return { - description: description, - tags: tags - }; - } - exports.parse = parse; - }(jsdoc = {})); +},{}],47:[function(require,module,exports){ +(function (global){ +'use strict'; - exports.version = utility.VERSION; - exports.parse = jsdoc.parse; - exports.parseType = typed.parseType; - exports.parseParamType = typed.parseParamType; - exports.unwrapComment = unwrapComment; - exports.Syntax = shallowCopy(typed.Syntax); - exports.Error = utility.DoctrineError; - exports.type = { - Syntax: exports.Syntax, - parseType: typed.parseType, - parseParamType: typed.parseParamType, - stringify: typed.stringify - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: -},{"./typed":11,"./utility":12,"esutils":97,"isarray":108}],11:[function(require,module,exports){ -/* - * @fileoverview Type expression parser. - * @author Yusuke Suzuki - * @author Dan Tao - * @author Andrew Eisenberg +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT */ -// "typed", the Type Expression Parser for doctrine. - -(function () { - 'use strict'; - - var Syntax, - Token, - source, - length, - index, - previous, - token, - value, - esutils, - utility; - - esutils = require('esutils'); - utility = require('./utility'); - - Syntax = { - NullableLiteral: 'NullableLiteral', - AllLiteral: 'AllLiteral', - NullLiteral: 'NullLiteral', - UndefinedLiteral: 'UndefinedLiteral', - VoidLiteral: 'VoidLiteral', - UnionType: 'UnionType', - ArrayType: 'ArrayType', - RecordType: 'RecordType', - FieldType: 'FieldType', - FunctionType: 'FunctionType', - ParameterType: 'ParameterType', - RestType: 'RestType', - NonNullableType: 'NonNullableType', - OptionalType: 'OptionalType', - NullableType: 'NullableType', - NameExpression: 'NameExpression', - TypeApplication: 'TypeApplication', - StringLiteralType: 'StringLiteralType', - NumericLiteralType: 'NumericLiteralType', - BooleanLiteralType: 'BooleanLiteralType' - }; +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - Token = { - ILLEGAL: 0, // ILLEGAL - DOT_LT: 1, // .< - REST: 2, // ... - LT: 3, // < - GT: 4, // > - LPAREN: 5, // ( - RPAREN: 6, // ) - LBRACE: 7, // { - RBRACE: 8, // } - LBRACK: 9, // [ - RBRACK: 10, // ] - COMMA: 11, // , - COLON: 12, // : - STAR: 13, // * - PIPE: 14, // | - QUESTION: 15, // ? - BANG: 16, // ! - EQUAL: 17, // = - NAME: 18, // name token - STRING: 19, // string - NUMBER: 20, // number - EOF: 21 - }; +function compare(a, b) { + if (a === b) { + return 0; + } - function isTypeName(ch) { - return '><(){}[],:*|?!='.indexOf(String.fromCharCode(ch)) === -1 && !esutils.code.isWhiteSpace(ch) && !esutils.code.isLineTerminator(ch); - } + var x = a.length; + var y = b.length; - function Context(previous, index, token, value) { - this._previous = previous; - this._index = index; - this._token = token; - this._value = value; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; } + } - Context.prototype.restore = function () { - previous = this._previous; - index = this._index; - token = this._token; - value = this._value; - }; - - Context.save = function () { - return new Context(previous, index, token, value); - }; + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} - function advance() { - var ch = source.charAt(index); - index += 1; - return ch; - } +// based on node assert, original notice: - function scanHexEscape(prefix) { - var i, len, ch, code = 0; +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - len = (prefix === 'u') ? 4 : 2; - for (i = 0; i < len; ++i) { - if (index < length && esutils.code.isHexDigit(source.charCodeAt(index))) { - ch = advance(); - code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); - } else { - return ''; - } - } - return String.fromCharCode(code); - } +var util = require('util/'); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = function () { + return function foo() {}.name === 'foo'; +}(); +function pToString(obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. - function scanString() { - var str = '', quote, ch, code, unescaped, restore; //TODO review removal octal = false - quote = source.charAt(index); - ++index; +var assert = module.exports = ok; - while (index < length) { - ch = advance(); +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) - if (ch === quote) { - quote = ''; - break; - } else if (ch === '\\') { - ch = advance(); - if (!esutils.code.isLineTerminator(ch.charCodeAt(0))) { - switch (ch) { - case 'n': - str += '\n'; - break; - case 'r': - str += '\r'; - break; - case 't': - str += '\t'; - break; - case 'u': - case 'x': - restore = index; - unescaped = scanHexEscape(ch); - if (unescaped) { - str += unescaped; - } else { - index = restore; - str += ch; - } - break; - case 'b': - str += '\b'; - break; - case 'f': - str += '\f'; - break; - case 'v': - str += '\v'; - break; - - default: - if (esutils.code.isOctalDigit(ch.charCodeAt(0))) { - code = '01234567'.indexOf(ch); - - // \0 is not octal escape sequence - // Deprecating unused code. TODO review removal - //if (code !== 0) { - // octal = true; - //} - - if (index < length && esutils.code.isOctalDigit(source.charCodeAt(index))) { - //TODO Review Removal octal = true; - code = code * 8 + '01234567'.indexOf(advance()); - - // 3 digits are only allowed when string starts - // with 0, 1, 2, 3 - if ('0123'.indexOf(ch) >= 0 && - index < length && - esutils.code.isOctalDigit(source.charCodeAt(index))) { - code = code * 8 + '01234567'.indexOf(advance()); - } - } - str += String.fromCharCode(code); - } else { - str += ch; - } - break; - } - } else { - if (ch === '\r' && source.charCodeAt(index) === 0x0A /* '\n' */) { - ++index; - } - } - } else if (esutils.code.isLineTerminator(ch.charCodeAt(0))) { - break; - } else { - str += ch; - } - } +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; - if (quote !== '') { - utility.throwError('unexpected quote'); - } + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } - value = str; - return Token.STRING; + this.stack = out; } + } +}; - function scanNumber() { - var number, ch; +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); - number = ''; - ch = source.charCodeAt(index); +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect(self.expected), 128); +} - if (ch !== 0x2E /* '.' */) { - number = advance(); - ch = source.charCodeAt(index); +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. - if (number === '0') { - if (ch === 0x78 /* 'x' */ || ch === 0x58 /* 'X' */) { - number += advance(); - while (index < length) { - ch = source.charCodeAt(index); - if (!esutils.code.isHexDigit(ch)) { - break; - } - number += advance(); - } +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. - if (number.length <= 2) { - // only 0x - utility.throwError('unexpected token'); - } +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} - if (index < length) { - ch = source.charCodeAt(index); - if (esutils.code.isIdentifierStartES5(ch)) { - utility.throwError('unexpected token'); - } - } - value = parseInt(number, 16); - return Token.NUMBER; - } +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; - if (esutils.code.isOctalDigit(ch)) { - number += advance(); - while (index < length) { - ch = source.charCodeAt(index); - if (!esutils.code.isOctalDigit(ch)) { - break; - } - number += advance(); - } +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. - if (index < length) { - ch = source.charCodeAt(index); - if (esutils.code.isIdentifierStartES5(ch) || esutils.code.isDecimalDigit(ch)) { - utility.throwError('unexpected token'); - } - } - value = parseInt(number, 8); - return Token.NUMBER; - } +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; - if (esutils.code.isDecimalDigit(ch)) { - utility.throwError('unexpected token'); - } - } +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); - while (index < length) { - ch = source.charCodeAt(index); - if (!esutils.code.isDecimalDigit(ch)) { - break; - } - number += advance(); - } - } +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; - if (ch === 0x2E /* '.' */) { - number += advance(); - while (index < length) { - ch = source.charCodeAt(index); - if (!esutils.code.isDecimalDigit(ch)) { - break; - } - number += advance(); - } - } +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); - if (ch === 0x65 /* 'e' */ || ch === 0x45 /* 'E' */) { - number += advance(); +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; - ch = source.charCodeAt(index); - if (ch === 0x2B /* '+' */ || ch === 0x2D /* '-' */) { - number += advance(); - } +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); - ch = source.charCodeAt(index); - if (esutils.code.isDecimalDigit(ch)) { - number += advance(); - while (index < length) { - ch = source.charCodeAt(index); - if (!esutils.code.isDecimalDigit(ch)) { - break; - } - number += advance(); - } - } else { - utility.throwError('unexpected token'); - } - } +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; - if (index < length) { - ch = source.charCodeAt(index); - if (esutils.code.isIdentifierStartES5(ch)) { - utility.throwError('unexpected token'); - } - } +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; - value = parseFloat(number); - return Token.NUMBER; - } +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); - function scanTypeName() { - var ch, ch2; + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; - value = advance(); - while (index < length && isTypeName(source.charCodeAt(index))) { - ch = source.charCodeAt(index); - if (ch === 0x2E /* '.' */) { - if ((index + 1) >= length) { - return Token.ILLEGAL; - } - ch2 = source.charCodeAt(index + 1); - if (ch2 === 0x3C /* '<' */) { - break; - } - } - value += advance(); - } - return Token.NAME; + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || (typeof actual === 'undefined' ? 'undefined' : _typeof(actual)) !== 'object') && (expected === null || (typeof expected === 'undefined' ? 'undefined' : _typeof(expected)) !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || { actual: [], expected: [] }; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } } - function next() { - var ch; + memos.actual.push(actual); + memos.expected.push(expected); - previous = index; + return objEquiv(actual, expected, strict, memos); + } +} - while (index < length && esutils.code.isWhiteSpace(source.charCodeAt(index))) { - advance(); - } - if (index >= length) { - token = Token.EOF; - return token; - } +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} - ch = source.charCodeAt(index); - switch (ch) { - case 0x27: /* ''' */ - case 0x22: /* '"' */ - token = scanString(); - return token; +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if (aIsArgs && !bIsArgs || !aIsArgs && bIsArgs) return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false; + } + return true; +} - case 0x3A: /* ':' */ - advance(); - token = Token.COLON; - return token; +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); - case 0x2C: /* ',' */ - advance(); - token = Token.COMMA; - return token; +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; - case 0x28: /* '(' */ - advance(); - token = Token.LPAREN; - return token; +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} - case 0x29: /* ')' */ - advance(); - token = Token.RPAREN; - return token; +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); - case 0x5B: /* '[' */ - advance(); - token = Token.LBRACK; - return token; +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; - case 0x5D: /* ']' */ - advance(); - token = Token.RBRACK; - return token; +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - case 0x7B: /* '{' */ - advance(); - token = Token.LBRACE; - return token; +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; - case 0x7D: /* '}' */ - advance(); - token = Token.RBRACE; - return token; +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } - case 0x2E: /* '.' */ - if (index + 1 < length) { - ch = source.charCodeAt(index + 1); - if (ch === 0x3C /* '<' */) { - advance(); // '.' - advance(); // '<' - token = Token.DOT_LT; - return token; - } + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } - if (ch === 0x2E /* '.' */ && index + 2 < length && source.charCodeAt(index + 2) === 0x2E /* '.' */) { - advance(); // '.' - advance(); // '.' - advance(); // '.' - token = Token.REST; - return token; - } + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } - if (esutils.code.isDecimalDigit(ch)) { - token = scanNumber(); - return token; - } - } - token = Token.ILLEGAL; - return token; + if (Error.isPrototypeOf(expected)) { + return false; + } - case 0x3C: /* '<' */ - advance(); - token = Token.LT; - return token; + return expected.call({}, actual) === true; +} - case 0x3E: /* '>' */ - advance(); - token = Token.GT; - return token; +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} - case 0x2A: /* '*' */ - advance(); - token = Token.STAR; - return token; +function _throws(shouldThrow, block, expected, message) { + var actual; - case 0x7C: /* '|' */ - advance(); - token = Token.PIPE; - return token; + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } - case 0x3F: /* '?' */ - advance(); - token = Token.QUESTION; - return token; + if (typeof expected === 'string') { + message = expected; + expected = null; + } - case 0x21: /* '!' */ - advance(); - token = Token.BANG; - return token; + actual = _tryBlock(block); - case 0x3D: /* '=' */ - advance(); - token = Token.EQUAL; - return token; + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); - case 0x2D: /* '-' */ - token = scanNumber(); - return token; + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } - default: - if (esutils.code.isDecimalDigit(ch)) { - token = scanNumber(); - return token; - } + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; - // type string permits following case, - // - // namespace.module.MyClass - // - // this reduced 1 token TK_NAME - utility.assert(isTypeName(ch)); - token = scanTypeName(); - return token; - } - } + if (isUnwantedException && userProvidedMessage && expectedException(actual, expected) || isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } - function consume(target, text) { - utility.assert(token === target, text || 'consumed token not matched'); - next(); - } + if (shouldThrow && actual && expected && !expectedException(actual, expected) || !shouldThrow && actual) { + throw actual; + } +} - function expect(target, message) { - if (token !== target) { - utility.throwError(message || 'unexpected token'); +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function (block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function (block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function (err) { + if (err) throw err; +}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"util/":116}],48:[function(require,module,exports){ +'use strict'; + +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [begs.pop(), bi]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; } - next(); + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; } - // UnionType := '(' TypeUnionList ')' - // - // TypeUnionList := - // <> - // | NonemptyTypeUnionList - // - // NonemptyTypeUnionList := - // TypeExpression - // | TypeExpression '|' NonemptyTypeUnionList - function parseUnionType() { - var elements; - consume(Token.LPAREN, 'UnionType should start with ('); - elements = []; - if (token !== Token.RPAREN) { - while (true) { - elements.push(parseTypeExpression()); - if (token === Token.RPAREN) { - break; - } - expect(Token.PIPE); - } - } - consume(Token.RPAREN, 'UnionType should end with )'); - return { - type: Syntax.UnionType, - elements: elements - }; + if (begs.length) { + result = [left, right]; } + } - // ArrayType := '[' ElementTypeList ']' - // - // ElementTypeList := - // <> - // | TypeExpression - // | '...' TypeExpression - // | TypeExpression ',' ElementTypeList - function parseArrayType() { - var elements; - consume(Token.LBRACK, 'ArrayType should start with ['); - elements = []; - while (token !== Token.RBRACK) { - if (token === Token.REST) { - consume(Token.REST); - elements.push({ - type: Syntax.RestType, - expression: parseTypeExpression() - }); - break; - } else { - elements.push(parseTypeExpression()); - } - if (token !== Token.RBRACK) { - expect(Token.COMMA); - } - } - expect(Token.RBRACK); - return { - type: Syntax.ArrayType, - elements: elements - }; - } + return result; +} - function parseFieldName() { - var v = value; - if (token === Token.NAME || token === Token.STRING) { - next(); - return v; - } +},{}],49:[function(require,module,exports){ +'use strict'; - if (token === Token.NUMBER) { - consume(Token.NUMBER); - return String(v); - } +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); - utility.throwError('unexpected token'); - } +module.exports = expandTop; - // FieldType := - // FieldName - // | FieldName ':' TypeExpression - // - // FieldName := - // NameExpression - // | StringLiteral - // | NumberLiteral - // | ReservedIdentifier - function parseFieldType() { - var key; +var escSlash = '\0SLASH' + Math.random() + '\0'; +var escOpen = '\0OPEN' + Math.random() + '\0'; +var escClose = '\0CLOSE' + Math.random() + '\0'; +var escComma = '\0COMMA' + Math.random() + '\0'; +var escPeriod = '\0PERIOD' + Math.random() + '\0'; - key = parseFieldName(); - if (token === Token.COLON) { - consume(Token.COLON); - return { - type: Syntax.FieldType, - key: key, - value: parseTypeExpression() - }; - } - return { - type: Syntax.FieldType, - key: key, - value: null - }; - } +function numeric(str) { + return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); +} - // RecordType := '{' FieldTypeList '}' - // - // FieldTypeList := - // <> - // | FieldType - // | FieldType ',' FieldTypeList - function parseRecordType() { - var fields; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod); +} - consume(Token.LBRACE, 'RecordType should start with {'); - fields = []; - if (token === Token.COMMA) { - consume(Token.COMMA); - } else { - while (token !== Token.RBRACE) { - fields.push(parseFieldType()); - if (token !== Token.RBRACE) { - expect(Token.COMMA); - } - } - } - expect(Token.RBRACE); - return { - type: Syntax.RecordType, - fields: fields - }; - } +function unescapeBraces(str) { + return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.'); +} - // NameExpression := - // Identifier - // | TagIdentifier ':' Identifier - // - // Tag identifier is one of "module", "external" or "event" - // Identifier is the same as Token.NAME, including any dots, something like - // namespace.module.MyClass - function parseNameExpression() { - var name = value; - expect(Token.NAME); +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) return ['']; - if (token === Token.COLON && ( - name === 'module' || - name === 'external' || - name === 'event')) { - consume(Token.COLON); - name += ':' + value; - expect(Token.NAME); - } + var parts = []; + var m = balanced('{', '}', str); - return { - type: Syntax.NameExpression, - name: name - }; - } + if (!m) return str.split(','); - // TypeExpressionList := - // TopLevelTypeExpression - // | TopLevelTypeExpression ',' TypeExpressionList - function parseTypeExpressionList() { - var elements = []; + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - elements.push(parseTop()); - while (token === Token.COMMA) { - consume(Token.COMMA); - elements.push(parseTop()); - } - return elements; - } + p[p.length - 1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } - // TypeName := - // NameExpression - // | NameExpression TypeApplication - // - // TypeApplication := - // '.<' TypeExpressionList '>' - // | '<' TypeExpressionList '>' // this is extension of doctrine - function parseTypeName() { - var expr, applications; + parts.push.apply(parts, p); - expr = parseNameExpression(); - if (token === Token.DOT_LT || token === Token.LT) { - next(); - applications = parseTypeExpressionList(); - expect(Token.GT); - return { - type: Syntax.TypeApplication, - expression: expr, - applications: applications - }; - } - return expr; - } + return parts; +} - // ResultType := - // <> - // | ':' void - // | ':' TypeExpression - // - // BNF is above - // but, we remove <> pattern, so token is always TypeToken::COLON - function parseResultType() { - consume(Token.COLON, 'ResultType should start with :'); - if (token === Token.NAME && value === 'void') { - consume(Token.NAME); - return { - type: Syntax.VoidLiteral - }; - } - return parseTypeExpression(); - } +function expandTop(str) { + if (!str) return []; - // ParametersType := - // RestParameterType - // | NonRestParametersType - // | NonRestParametersType ',' RestParameterType - // - // RestParameterType := - // '...' - // '...' Identifier - // - // NonRestParametersType := - // ParameterType ',' NonRestParametersType - // | ParameterType - // | OptionalParametersType - // - // OptionalParametersType := - // OptionalParameterType - // | OptionalParameterType, OptionalParametersType - // - // OptionalParameterType := ParameterType= - // - // ParameterType := TypeExpression | Identifier ':' TypeExpression - // - // Identifier is "new" or "this" - function parseParametersType() { - var params = [], optionalSequence = false, expr, rest = false; + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } - while (token !== Token.RPAREN) { - if (token === Token.REST) { - // RestParameterType - consume(Token.REST); - rest = true; - } + return expand(escapeBraces(str), true).map(unescapeBraces); +} - expr = parseTypeExpression(); - if (expr.type === Syntax.NameExpression && token === Token.COLON) { - // Identifier ':' TypeExpression - consume(Token.COLON); - expr = { - type: Syntax.ParameterType, - name: expr.name, - expression: parseTypeExpression() - }; - } - if (token === Token.EQUAL) { - consume(Token.EQUAL); - expr = { - type: Syntax.OptionalType, - expression: expr - }; - optionalSequence = true; - } else { - if (optionalSequence) { - utility.throwError('unexpected token'); - } - } - if (rest) { - expr = { - type: Syntax.RestType, - expression: expr - }; - } - params.push(expr); - if (token !== Token.RPAREN) { - expect(Token.COMMA); - } - } - return params; - } +function identity(e) { + return e; +} - // FunctionType := 'function' FunctionSignatureType - // - // FunctionSignatureType := - // | TypeParameters '(' ')' ResultType - // | TypeParameters '(' ParametersType ')' ResultType - // | TypeParameters '(' 'this' ':' TypeName ')' ResultType - // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType - function parseFunctionType() { - var isNew, thisBinding, params, result, fnType; - utility.assert(token === Token.NAME && value === 'function', 'FunctionType should start with \'function\''); - consume(Token.NAME); +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return (/^-?0\d/.test(el) + ); +} - // Google Closure Compiler is not implementing TypeParameters. - // So we do not. if we don't get '(', we see it as error. - expect(Token.LPAREN); +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} - isNew = false; - params = []; - thisBinding = null; - if (token !== Token.RPAREN) { - // ParametersType or 'this' - if (token === Token.NAME && - (value === 'this' || value === 'new')) { - // 'this' or 'new' - // 'new' is Closure Compiler extension - isNew = value === 'new'; - consume(Token.NAME); - expect(Token.COLON); - thisBinding = parseTypeName(); - if (token === Token.COMMA) { - consume(Token.COMMA); - params = parseParametersType(); - } - } else { - params = parseParametersType(); - } - } +function expand(str, isTop) { + var expansions = []; - expect(Token.RPAREN); + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - result = null; - if (token === Token.COLON) { - result = parseResultType(); - } + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } - fnType = { - type: Syntax.FunctionType, - params: params, - result: result - }; - if (thisBinding) { - // avoid adding null 'new' and 'this' properties - fnType['this'] = thisBinding; - if (isNew) { - fnType['new'] = true; - } - } - return fnType; + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length ? expand(m.post, false) : ['']; + return post.map(function (p) { + return m.pre + n[0] + p; + }); + } } + } - // BasicTypeExpression := - // '*' - // | 'null' - // | 'undefined' - // | TypeName - // | FunctionType - // | UnionType - // | RecordType - // | ArrayType - function parseBasicTypeExpression() { - var context; - switch (token) { - case Token.STAR: - consume(Token.STAR); - return { - type: Syntax.AllLiteral - }; + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - case Token.LPAREN: - return parseUnionType(); + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length ? expand(m.post, false) : ['']; - case Token.LBRACK: - return parseArrayType(); + var N; - case Token.LBRACE: - return parseRecordType(); + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - case Token.NAME: - if (value === 'null') { - consume(Token.NAME); - return { - type: Syntax.NullLiteral - }; - } + N = []; - if (value === 'undefined') { - consume(Token.NAME); - return { - type: Syntax.UndefinedLiteral - }; - } + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) c = '-' + z + c.slice(1);else c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function (el) { + return expand(el, false); + }); + } - if (value === 'true' || value === 'false') { - consume(Token.NAME); - return { - type: Syntax.BooleanLiteralType, - value: value === 'true' - }; - } + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) expansions.push(expansion); + } + } - context = Context.save(); - if (value === 'function') { - try { - return parseFunctionType(); - } catch (e) { - context.restore(); - } - } + return expansions; +} - return parseTypeName(); +},{"balanced-match":48,"concat-map":51}],50:[function(require,module,exports){ +'use strict'; - case Token.STRING: - next(); - return { - type: Syntax.StringLiteralType, - value: value - }; +/** + * slice() reference. + */ - case Token.NUMBER: - next(); - return { - type: Syntax.NumericLiteralType, - value: value - }; +var slice = Array.prototype.slice; - default: - utility.throwError('unexpected token'); - } - } +/** + * Expose `co`. + */ - // TypeExpression := - // BasicTypeExpression - // | '?' BasicTypeExpression - // | '!' BasicTypeExpression - // | BasicTypeExpression '?' - // | BasicTypeExpression '!' - // | '?' - // | BasicTypeExpression '[]' - function parseTypeExpression() { - var expr; +module.exports = co['default'] = co.co = co; - if (token === Token.QUESTION) { - consume(Token.QUESTION); - if (token === Token.COMMA || token === Token.EQUAL || token === Token.RBRACE || - token === Token.RPAREN || token === Token.PIPE || token === Token.EOF || - token === Token.RBRACK || token === Token.GT) { - return { - type: Syntax.NullableLiteral - }; - } - return { - type: Syntax.NullableType, - expression: parseBasicTypeExpression(), - prefix: true - }; - } +/** + * Wrap the given generator `fn` into a + * function that returns a promise. + * This is a separate function so that + * every `co()` call doesn't create a new, + * unnecessary closure. + * + * @param {GeneratorFunction} fn + * @return {Function} + * @api public + */ - if (token === Token.BANG) { - consume(Token.BANG); - return { - type: Syntax.NonNullableType, - expression: parseBasicTypeExpression(), - prefix: true - }; - } +co.wrap = function (fn) { + createPromise.__generatorFunction__ = fn; + return createPromise; + function createPromise() { + return co.call(this, fn.apply(this, arguments)); + } +}; - expr = parseBasicTypeExpression(); - if (token === Token.BANG) { - consume(Token.BANG); - return { - type: Syntax.NonNullableType, - expression: expr, - prefix: false - }; - } +/** + * Execute the generator function or a generator + * and return a promise. + * + * @param {Function} fn + * @return {Promise} + * @api public + */ - if (token === Token.QUESTION) { - consume(Token.QUESTION); - return { - type: Syntax.NullableType, - expression: expr, - prefix: false - }; - } +function co(gen) { + var ctx = this; + var args = slice.call(arguments, 1); - if (token === Token.LBRACK) { - consume(Token.LBRACK); - expect(Token.RBRACK, 'expected an array-style type declaration (' + value + '[])'); - return { - type: Syntax.TypeApplication, - expression: { - type: Syntax.NameExpression, - name: 'Array' - }, - applications: [expr] - }; - } + // we wrap everything in a promise to avoid promise chaining, + // which leads to memory leak errors. + // see https://github.com/tj/co/issues/180 + return new Promise(function (resolve, reject) { + if (typeof gen === 'function') gen = gen.apply(ctx, args); + if (!gen || typeof gen.next !== 'function') return resolve(gen); - return expr; - } + onFulfilled(); - // TopLevelTypeExpression := - // TypeExpression - // | TypeUnionList - // - // This rule is Google Closure Compiler extension, not ES4 - // like, - // { number | string } - // If strict to ES4, we should write it as - // { (number|string) } - function parseTop() { - var expr, elements; + /** + * @param {Mixed} res + * @return {Promise} + * @api private + */ - expr = parseTypeExpression(); - if (token !== Token.PIPE) { - return expr; - } + function onFulfilled(res) { + var ret; + try { + ret = gen.next(res); + } catch (e) { + return reject(e); + } + next(ret); + } - elements = [expr]; - consume(Token.PIPE); - while (true) { - elements.push(parseTypeExpression()); - if (token !== Token.PIPE) { - break; - } - consume(Token.PIPE); - } + /** + * @param {Error} err + * @return {Promise} + * @api private + */ - return { - type: Syntax.UnionType, - elements: elements - }; + function onRejected(err) { + var ret; + try { + ret = gen.throw(err); + } catch (e) { + return reject(e); + } + next(ret); } - function parseTopParamType() { - var expr; + /** + * Get the next value in the generator, + * return a promise. + * + * @param {Object} ret + * @return {Promise} + * @api private + */ - if (token === Token.REST) { - consume(Token.REST); - return { - type: Syntax.RestType, - expression: parseTop() - }; - } + function next(ret) { + if (ret.done) return resolve(ret.value); + var value = toPromise.call(ctx, ret.value); + if (value && isPromise(value)) return value.then(onFulfilled, onRejected); + return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String(ret.value) + '"')); + } + }); +} - expr = parseTop(); - if (token === Token.EQUAL) { - consume(Token.EQUAL); - return { - type: Syntax.OptionalType, - expression: expr - }; - } +/** + * Convert a `yield`ed value into a promise. + * + * @param {Mixed} obj + * @return {Promise} + * @api private + */ - return expr; - } +function toPromise(obj) { + if (!obj) return obj; + if (isPromise(obj)) return obj; + if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj); + if ('function' == typeof obj) return thunkToPromise.call(this, obj); + if (Array.isArray(obj)) return arrayToPromise.call(this, obj); + if (isObject(obj)) return objectToPromise.call(this, obj); + return obj; +} - function parseType(src, opt) { - var expr; +/** + * Convert a thunk to a promise. + * + * @param {Function} + * @return {Promise} + * @api private + */ - source = src; - length = source.length; - index = 0; - previous = 0; +function thunkToPromise(fn) { + var ctx = this; + return new Promise(function (resolve, reject) { + fn.call(ctx, function (err, res) { + if (err) return reject(err); + if (arguments.length > 2) res = slice.call(arguments, 1); + resolve(res); + }); + }); +} - next(); - expr = parseTop(); +/** + * Convert an array of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Array} obj + * @return {Promise} + * @api private + */ - if (opt && opt.midstream) { - return { - expression: expr, - index: previous - }; - } +function arrayToPromise(obj) { + return Promise.all(obj.map(toPromise, this)); +} - if (token !== Token.EOF) { - utility.throwError('not reach to EOF'); - } +/** + * Convert an object of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Object} obj + * @return {Promise} + * @api private + */ - return expr; - } +function objectToPromise(obj) { + var results = new obj.constructor(); + var keys = Object.keys(obj); + var promises = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var promise = toPromise.call(this, obj[key]); + if (promise && isPromise(promise)) defer(promise, key);else results[key] = obj[key]; + } + return Promise.all(promises).then(function () { + return results; + }); - function parseParamType(src, opt) { - var expr; + function defer(promise, key) { + // predefine the key in the result + results[key] = undefined; + promises.push(promise.then(function (res) { + results[key] = res; + })); + } +} - source = src; - length = source.length; - index = 0; - previous = 0; +/** + * Check if `obj` is a promise. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ - next(); - expr = parseTopParamType(); +function isPromise(obj) { + return 'function' == typeof obj.then; +} - if (opt && opt.midstream) { - return { - expression: expr, - index: previous - }; - } +/** + * Check if `obj` is a generator. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ - if (token !== Token.EOF) { - utility.throwError('not reach to EOF'); - } +function isGenerator(obj) { + return 'function' == typeof obj.next && 'function' == typeof obj.throw; +} - return expr; - } +/** + * Check if `obj` is a generator function. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ +function isGeneratorFunction(obj) { + var constructor = obj.constructor; + if (!constructor) return false; + if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true; + return isGenerator(constructor.prototype); +} - function stringifyImpl(node, compact, topLevel) { - var result, i, iz; +/** + * Check for plain object. + * + * @param {Mixed} val + * @return {Boolean} + * @api private + */ - switch (node.type) { - case Syntax.NullableLiteral: - result = '?'; - break; +function isObject(val) { + return Object == val.constructor; +} - case Syntax.AllLiteral: - result = '*'; - break; +},{}],51:[function(require,module,exports){ +'use strict'; - case Syntax.NullLiteral: - result = 'null'; - break; +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x);else res.push(x); + } + return res; +}; - case Syntax.UndefinedLiteral: - result = 'undefined'; - break; +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - case Syntax.VoidLiteral: - result = 'void'; - break; +},{}],52:[function(require,module,exports){ +(function (process){ +'use strict'; - case Syntax.UnionType: - if (!topLevel) { - result = '('; - } else { - result = ''; - } +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - for (i = 0, iz = node.elements.length; i < iz; ++i) { - result += stringifyImpl(node.elements[i], compact); - if ((i + 1) !== iz) { - result += '|'; - } - } +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - if (!topLevel) { - result += ')'; - } - break; +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); - case Syntax.ArrayType: - result = '['; - for (i = 0, iz = node.elements.length; i < iz; ++i) { - result += stringifyImpl(node.elements[i], compact); - if ((i + 1) !== iz) { - result += compact ? ',' : ', '; - } - } - result += ']'; - break; +/** + * Colors. + */ - case Syntax.RecordType: - result = '{'; - for (i = 0, iz = node.fields.length; i < iz; ++i) { - result += stringifyImpl(node.fields[i], compact); - if ((i + 1) !== iz) { - result += compact ? ',' : ', '; - } - } - result += '}'; - break; +exports.colors = ['lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson']; - case Syntax.FieldType: - if (node.value) { - result = node.key + (compact ? ':' : ': ') + stringifyImpl(node.value, compact); - } else { - result = node.key; - } - break; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - case Syntax.FunctionType: - result = compact ? 'function(' : 'function ('; +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } - if (node['this']) { - if (node['new']) { - result += (compact ? 'new:' : 'new: '); - } else { - result += (compact ? 'this:' : 'this: '); - } + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || + // is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || + // double check webkit in userAgent just in case we are in a worker + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); +} - result += stringifyImpl(node['this'], compact); +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - if (node.params.length !== 0) { - result += compact ? ',' : ', '; - } - } +exports.formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; - for (i = 0, iz = node.params.length; i < iz; ++i) { - result += stringifyImpl(node.params[i], compact); - if ((i + 1) !== iz) { - result += compact ? ',' : ', '; - } - } +/** + * Colorize log arguments if enabled. + * + * @api public + */ - result += ')'; +function formatArgs(args) { + var useColors = this.useColors; - if (node.result) { - result += (compact ? ':' : ': ') + stringifyImpl(node.result, compact); - } - break; + args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); - case Syntax.ParameterType: - result = node.name + (compact ? ':' : ': ') + stringifyImpl(node.expression, compact); - break; + if (!useColors) return; - case Syntax.RestType: - result = '...'; - if (node.expression) { - result += stringifyImpl(node.expression, compact); - } - break; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - case Syntax.NonNullableType: - if (node.prefix) { - result = '!' + stringifyImpl(node.expression, compact); - } else { - result = stringifyImpl(node.expression, compact) + '!'; - } - break; + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function (match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - case Syntax.OptionalType: - result = stringifyImpl(node.expression, compact) + '='; - break; + args.splice(lastC, 0, c); +} - case Syntax.NullableType: - if (node.prefix) { - result = '?' + stringifyImpl(node.expression, compact); - } else { - result = stringifyImpl(node.expression, compact) + '?'; - } - break; +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ - case Syntax.NameExpression: - result = node.name; - break; +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments); +} - case Syntax.TypeApplication: - result = stringifyImpl(node.expression, compact) + '.<'; - for (i = 0, iz = node.applications.length; i < iz; ++i) { - result += stringifyImpl(node.applications[i], compact); - if ((i + 1) !== iz) { - result += compact ? ',' : ', '; - } - } - result += '>'; - break; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - case Syntax.StringLiteralType: - result = '"' + node.value + '"'; - break; +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch (e) {} +} - case Syntax.NumericLiteralType: - result = String(node.value); - break; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - case Syntax.BooleanLiteralType: - result = String(node.value); - break; +function load() { + var r; + try { + r = exports.storage.debug; + } catch (e) {} - default: - utility.throwError('Unknown type ' + node.type); - } + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - return result; - } + return r; +} - function stringify(node, options) { - if (options == null) { - options = {}; - } - return stringifyImpl(node, options.compact, options.topLevel); - } +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - exports.parseType = parseType; - exports.parseParamType = parseParamType; - exports.stringify = stringify; - exports.Syntax = Syntax; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ +exports.enable(load()); -},{"./utility":12,"esutils":97}],12:[function(require,module,exports){ -/* - * @fileoverview Utilities for Doctrine - * @author Yusuke Suzuki +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private */ +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} -(function () { - 'use strict'; - - var VERSION; +}).call(this,require('_process')) +},{"./debug":53,"_process":104}],53:[function(require,module,exports){ +'use strict'; - VERSION = require('../package.json').version; - exports.VERSION = VERSION; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - function DoctrineError(message) { - this.name = 'DoctrineError'; - this.message = message; - } - DoctrineError.prototype = (function () { - var Middle = function () { }; - Middle.prototype = Error.prototype; - return new Middle(); - }()); - DoctrineError.prototype.constructor = DoctrineError; - exports.DoctrineError = DoctrineError; +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); - function throwError(message) { - throw new DoctrineError(message); - } - exports.throwError = throwError; +/** + * The currently active debug mode names, and names to skip. + */ - exports.assert = require('assert'); -}()); +exports.names = []; +exports.skips = []; -/* vim: set sw=4 ts=4 et tw=80 : */ +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ -},{"../package.json":13,"assert":5}],13:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "doctrine@^2.0.0", - "scope": null, - "escapedName": "doctrine", - "name": "doctrine", - "rawSpec": "^2.0.0", - "spec": ">=2.0.0 <3.0.0", - "type": "range" - }, - "D:\\users\\r2g\\exps\\eslint-3.19.0" - ] - ], - "_from": "doctrine@>=2.0.0 <3.0.0", - "_id": "doctrine@2.0.0", - "_inCache": true, - "_location": "/doctrine", - "_nodeVersion": "4.4.2", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/doctrine-2.0.0.tgz_1479232728285_0.34204454137943685" - }, - "_npmUser": { - "name": "nzakas", - "email": "nicholas@nczconsulting.com" - }, - "_npmVersion": "2.15.0", - "_phantomChildren": {}, - "_requested": { - "raw": "doctrine@^2.0.0", - "scope": null, - "escapedName": "doctrine", - "name": "doctrine", - "rawSpec": "^2.0.0", - "spec": ">=2.0.0 <3.0.0", - "type": "range" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.0.0.tgz", - "_shasum": "c73d8d2909d22291e1a007a395804da8b665fe63", - "_shrinkwrap": null, - "_spec": "doctrine@^2.0.0", - "_where": "D:\\users\\r2g\\exps\\eslint-3.19.0", - "bugs": { - "url": "https://github.com/eslint/doctrine/issues" - }, - "dependencies": { - "esutils": "^2.0.2", - "isarray": "^1.0.0" - }, - "description": "JSDoc parser", - "devDependencies": { - "coveralls": "^2.11.2", - "dateformat": "^1.0.11", - "eslint": "^1.10.3", - "eslint-release": "^0.10.0", - "istanbul": "^0.4.1", - "linefix": "^0.1.1", - "mocha": "^2.3.3", - "npm-license": "^0.3.1", - "semver": "^5.0.3", - "shelljs": "^0.5.3", - "shelljs-nodecli": "^0.1.1", - "should": "^5.0.1" - }, - "directories": { - "lib": "./lib" - }, - "dist": { - "shasum": "c73d8d2909d22291e1a007a395804da8b665fe63", - "tarball": "https://registry.npmjs.org/doctrine/-/doctrine-2.0.0.tgz" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "lib", - "LICENSE.BSD", - "LICENSE.closure-compiler", - "LICENSE.esprima", - "README.md" - ], - "gitHead": "46c600f27f54b3ab6b0b8a9ac9f97c807ffa95ef", - "homepage": "https://github.com/eslint/doctrine", - "license": "Apache-2.0", - "main": "lib/doctrine.js", - "maintainers": [ - { - "name": "constellation", - "email": "utatane.tea@gmail.com" - }, - { - "name": "eslint", - "email": "nicholas+eslint@nczconsulting.com" - }, - { - "name": "nzakas", - "email": "nicholas@nczconsulting.com" - } - ], - "name": "doctrine", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/eslint/doctrine.git" - }, - "scripts": { - "alpharelease": "eslint-prerelease alpha", - "betarelease": "eslint-prerelease beta", - "ci-release": "eslint-ci-release", - "lint": "eslint lib/", - "release": "eslint-release", - "test": "npm run lint && node Makefile.js test" - }, - "version": "2.0.0" -} +exports.formatters = {}; -},{}],14:[function(require,module,exports){ -// Inspired by Google Closure: -// http://closure-library.googlecode.com/svn/docs/ -// closure_goog_array_array.js.html#goog.array.clear +/** + * Previous log timestamp. + */ -"use strict"; +var prevTime; -var value = require("../../object/valid-value"); +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -module.exports = function () { - value(this).length = 0; - return this; -}; +function selectColor(namespace) { + var hash = 0, + i; -},{"../../object/valid-value":51}],15:[function(require,module,exports){ -"use strict"; + for (i in namespace) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -var numberIsNaN = require("../../number/is-nan") - , toPosInt = require("../../number/to-pos-integer") - , value = require("../../object/valid-value") - , indexOf = Array.prototype.indexOf - , objHasOwnProperty = Object.prototype.hasOwnProperty - , abs = Math.abs - , floor = Math.floor; - -module.exports = function (searchElement /*, fromIndex*/) { - var i, length, fromIndex, val; - if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments); - - length = toPosInt(value(this).length); - fromIndex = arguments[1]; - if (isNaN(fromIndex)) fromIndex = 0; - else if (fromIndex >= 0) fromIndex = floor(fromIndex); - else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); - - for (i = fromIndex; i < length; ++i) { - if (objHasOwnProperty.call(this, i)) { - val = this[i]; - if (numberIsNaN(val)) return i; // Jslint: ignore - } - } - return -1; -}; + return exports.colors[Math.abs(hash) % exports.colors.length]; +} -},{"../../number/is-nan":25,"../../number/to-pos-integer":29,"../../object/valid-value":51}],16:[function(require,module,exports){ -"use strict"; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -module.exports = require("./is-implemented")() - ? Array.from - : require("./shim"); +function createDebug(namespace) { -},{"./is-implemented":17,"./shim":18}],17:[function(require,module,exports){ -"use strict"; + function debug() { + // disabled? + if (!debug.enabled) return; -module.exports = function () { - var from = Array.from, arr, result; - if (typeof from !== "function") return false; - arr = ["raz", "dwa"]; - result = from(arr); - return Boolean(result && (result !== arr) && (result[1] === "dwa")); -}; + var self = debug; -},{}],18:[function(require,module,exports){ -"use strict"; + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -var iteratorSymbol = require("es6-symbol").iterator - , isArguments = require("../../function/is-arguments") - , isFunction = require("../../function/is-function") - , toPosInt = require("../../number/to-pos-integer") - , callable = require("../../object/valid-callable") - , validValue = require("../../object/valid-value") - , isValue = require("../../object/is-value") - , isString = require("../../string/is-string") - , isArray = Array.isArray - , call = Function.prototype.call - , desc = { configurable: true, enumerable: true, writable: true, value: null } - , defineProperty = Object.defineProperty; - -// eslint-disable-next-line complexity -module.exports = function (arrayLike /*, mapFn, thisArg*/) { - var mapFn = arguments[1] - , thisArg = arguments[2] - , Context - , i - , j - , arr - , length - , code - , iterator - , result - , getIterator - , value; - - arrayLike = Object(validValue(arrayLike)); - - if (isValue(mapFn)) callable(mapFn); - if (!this || this === Array || !isFunction(this)) { - // Result: Plain array - if (!mapFn) { - if (isArguments(arrayLike)) { - // Source: Arguments - length = arrayLike.length; - if (length !== 1) return Array.apply(null, arrayLike); - arr = new Array(1); - arr[0] = arrayLike[0]; - return arr; - } - if (isArray(arrayLike)) { - // Source: Array - arr = new Array(length = arrayLike.length); - for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; - return arr; - } - } - arr = []; - } else { - // Result: Non plain array - Context = this; - } + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } - if (!isArray(arrayLike)) { - if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { - // Source: Iterator - iterator = callable(getIterator).call(arrayLike); - if (Context) arr = new Context(); - result = iterator.next(); - i = 0; - while (!result.done) { - value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; - if (Context) { - desc.value = value; - defineProperty(arr, i, desc); - } else { - arr[i] = value; - } - result = iterator.next(); - ++i; - } - length = i; - } else if (isString(arrayLike)) { - // Source: String - length = arrayLike.length; - if (Context) arr = new Context(); - for (i = 0, j = 0; i < length; ++i) { - value = arrayLike[i]; - if (i + 1 < length) { - code = value.charCodeAt(0); - // eslint-disable-next-line max-depth - if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i]; - } - value = mapFn ? call.call(mapFn, thisArg, value, j) : value; - if (Context) { - desc.value = value; - defineProperty(arr, j, desc); - } else { - arr[j] = value; - } - ++j; - } - length = j; - } - } - if (length === undefined) { - // Source: array or array-like - length = toPosInt(arrayLike.length); - if (Context) arr = new Context(length); - for (i = 0; i < length; ++i) { - value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; - if (Context) { - desc.value = value; - defineProperty(arr, i, desc); - } else { - arr[i] = value; - } - } - } - if (Context) { - desc.value = null; - arr.length = length; - } - return arr; -}; + args[0] = exports.coerce(args[0]); -},{"../../function/is-arguments":19,"../../function/is-function":20,"../../number/to-pos-integer":29,"../../object/is-value":39,"../../object/valid-callable":49,"../../object/valid-value":51,"../../string/is-string":55,"es6-symbol":70}],19:[function(require,module,exports){ -"use strict"; + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } -var objToString = Object.prototype.toString - , id = objToString.call( - (function () { - return arguments; - })() -); - -module.exports = function (value) { - return objToString.call(value) === id; -}; - -},{}],20:[function(require,module,exports){ -"use strict"; - -var objToString = Object.prototype.toString, id = objToString.call(require("./noop")); + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); -module.exports = function (value) { - return typeof value === "function" && objToString.call(value) === id; -}; + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -},{"./noop":21}],21:[function(require,module,exports){ -"use strict"; + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); -// eslint-disable-next-line no-empty-function -module.exports = function () {}; + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } -},{}],22:[function(require,module,exports){ -"use strict"; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -module.exports = require("./is-implemented")() - ? Math.sign - : require("./shim"); + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } -},{"./is-implemented":23,"./shim":24}],23:[function(require,module,exports){ -"use strict"; + return debug; +} -module.exports = function () { - var sign = Math.sign; - if (typeof sign !== "function") return false; - return (sign(10) === 1) && (sign(-20) === -1); -}; +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ -},{}],24:[function(require,module,exports){ -"use strict"; +function enable(namespaces) { + exports.save(namespaces); -module.exports = function (value) { - value = Number(value); - if (isNaN(value) || (value === 0)) return value; - return value > 0 ? 1 : -1; -}; + exports.names = []; + exports.skips = []; -},{}],25:[function(require,module,exports){ -"use strict"; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; -module.exports = require("./is-implemented")() - ? Number.isNaN - : require("./shim"); + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} -},{"./is-implemented":26,"./shim":27}],26:[function(require,module,exports){ -"use strict"; +/** + * Disable debug output. + * + * @api public + */ -module.exports = function () { - var numberIsNaN = Number.isNaN; - if (typeof numberIsNaN !== "function") return false; - return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34); -}; +function disable() { + exports.enable(''); +} -},{}],27:[function(require,module,exports){ -"use strict"; +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ -module.exports = function (value) { - // eslint-disable-next-line no-self-compare - return value !== value; -}; +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} -},{}],28:[function(require,module,exports){ -"use strict"; +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ -var sign = require("../math/sign") +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} - , abs = Math.abs, floor = Math.floor; +},{"ms":94}],54:[function(require,module,exports){ +'use strict'; -module.exports = function (value) { - if (isNaN(value)) return 0; - value = Number(value); - if ((value === 0) || !isFinite(value)) return value; - return sign(value) * floor(abs(value)); -}; +/* + * @fileoverview Main Doctrine object + * @author Yusuke Suzuki + * @author Dan Tao + * @author Andrew Eisenberg + */ -},{"../math/sign":22}],29:[function(require,module,exports){ -"use strict"; +(function () { + 'use strict'; -var toInteger = require("./to-integer") + var typed, utility, isArray, jsdoc, esutils, hasOwnProperty; - , max = Math.max; + esutils = require('esutils'); + isArray = require('isarray'); + typed = require('./typed'); + utility = require('./utility'); -module.exports = function (value) { - return max(0, toInteger(value)); -}; + function sliceSource(source, index, last) { + return source.slice(index, last); + } -},{"./to-integer":28}],30:[function(require,module,exports){ -// Internal method, used by iteration functions. -// Calls a function for each key-value pair found in object -// Optionally takes compareFn to iterate object in specific order + hasOwnProperty = function () { + var func = Object.prototype.hasOwnProperty; + return function hasOwnProperty(obj, name) { + return func.call(obj, name); + }; + }(); -"use strict"; + function shallowCopy(obj) { + var ret = {}, + key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } -var callable = require("./valid-callable") - , value = require("./valid-value") - , bind = Function.prototype.bind - , call = Function.prototype.call - , keys = Object.keys - , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; - -module.exports = function (method, defVal) { - return function (obj, cb /*, thisArg, compareFn*/) { - var list, thisArg = arguments[2], compareFn = arguments[3]; - obj = Object(value(obj)); - callable(cb); - - list = keys(obj); - if (compareFn) { - list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined); - } - if (typeof method !== "function") method = list[method]; - return call.call(method, list, function (key, index) { - if (!objPropertyIsEnumerable.call(obj, key)) return defVal; - return call.call(cb, thisArg, obj[key], key, obj, index); - }); - }; -}; + function isASCIIAlphanumeric(ch) { + return ch >= 0x61 /* 'a' */ && ch <= 0x7A /* 'z' */ || ch >= 0x41 /* 'A' */ && ch <= 0x5A /* 'Z' */ || ch >= 0x30 /* '0' */ && ch <= 0x39 /* '9' */; + } -},{"./valid-callable":49,"./valid-value":51}],31:[function(require,module,exports){ -"use strict"; + function isParamTitle(title) { + return title === 'param' || title === 'argument' || title === 'arg'; + } -module.exports = require("./is-implemented")() - ? Object.assign - : require("./shim"); + function isReturnTitle(title) { + return title === 'return' || title === 'returns'; + } -},{"./is-implemented":32,"./shim":33}],32:[function(require,module,exports){ -"use strict"; + function isProperty(title) { + return title === 'property' || title === 'prop'; + } -module.exports = function () { - var assign = Object.assign, obj; - if (typeof assign !== "function") return false; - obj = { foo: "raz" }; - assign(obj, { bar: "dwa" }, { trzy: "trzy" }); - return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy"; -}; + function isNameParameterRequired(title) { + return isParamTitle(title) || isProperty(title) || title === 'alias' || title === 'this' || title === 'mixes' || title === 'requires'; + } -},{}],33:[function(require,module,exports){ -"use strict"; + function isAllowedName(title) { + return isNameParameterRequired(title) || title === 'const' || title === 'constant'; + } -var keys = require("../keys") - , value = require("../valid-value") - , max = Math.max; - -module.exports = function (dest, src /*, …srcn*/) { - var error, i, length = max(arguments.length, 2), assign; - dest = Object(value(dest)); - assign = function (key) { - try { - dest[key] = src[key]; - } catch (e) { - if (!error) error = e; - } - }; - for (i = 1; i < length; ++i) { - src = arguments[i]; - keys(src).forEach(assign); - } - if (error !== undefined) throw error; - return dest; -}; + function isAllowedNested(title) { + return isProperty(title) || isParamTitle(title); + } -},{"../keys":40,"../valid-value":51}],34:[function(require,module,exports){ -"use strict"; + function isAllowedOptional(title) { + return isProperty(title) || isParamTitle(title); + } -var aFrom = require("../array/from") - , assign = require("./assign") - , value = require("./valid-value"); - -module.exports = function (obj/*, propertyNames, options*/) { - var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]); - if (copy !== obj && !propertyNames) return copy; - var result = {}; - if (propertyNames) { - aFrom(propertyNames, function (propertyName) { - if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; - }); - } else { - assign(result, obj); - } - return result; -}; + function isTypeParameterRequired(title) { + return isParamTitle(title) || isReturnTitle(title) || title === 'define' || title === 'enum' || title === 'implements' || title === 'this' || title === 'type' || title === 'typedef' || isProperty(title); + } -},{"../array/from":16,"./assign":31,"./valid-value":51}],35:[function(require,module,exports){ -// Workaround for http://code.google.com/p/v8/issues/detail?id=2804 + // Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick when a type is optional/required + // This would require changes to 'parseType' + function isAllowedType(title) { + return isTypeParameterRequired(title) || title === 'throws' || title === 'const' || title === 'constant' || title === 'namespace' || title === 'member' || title === 'var' || title === 'module' || title === 'constructor' || title === 'class' || title === 'extends' || title === 'augments' || title === 'public' || title === 'private' || title === 'protected'; + } -"use strict"; + function trim(str) { + return str.replace(/^\s+/, '').replace(/\s+$/, ''); + } -var create = Object.create, shim; + function unwrapComment(doc) { + // JSDoc comment is following form + // /** + // * ....... + // */ + // remove /**, */ and * + var BEFORE_STAR = 0, + STAR = 1, + AFTER_STAR = 2, + index, + len, + mode, + result, + ch; -if (!require("./set-prototype-of/is-implemented")()) { - shim = require("./set-prototype-of/shim"); -} + doc = doc.replace(/^\/\*\*?/, '').replace(/\*\/$/, ''); + index = 0; + len = doc.length; + mode = BEFORE_STAR; + result = ''; -module.exports = (function () { - var nullObject, polyProps, desc; - if (!shim) return create; - if (shim.level !== 1) return create; + while (index < len) { + ch = doc.charCodeAt(index); + switch (mode) { + case BEFORE_STAR: + if (esutils.code.isLineTerminator(ch)) { + result += String.fromCharCode(ch); + } else if (ch === 0x2A /* '*' */) { + mode = STAR; + } else if (!esutils.code.isWhiteSpace(ch)) { + result += String.fromCharCode(ch); + mode = AFTER_STAR; + } + break; - nullObject = {}; - polyProps = {}; - desc = { - configurable: false, - enumerable: false, - writable: true, - value: undefined - }; - Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { - if (name === "__proto__") { - polyProps[name] = { - configurable: true, - enumerable: false, - writable: true, - value: undefined - }; - return; - } - polyProps[name] = desc; - }); - Object.defineProperties(nullObject, polyProps); - - Object.defineProperty(shim, "nullPolyfill", { - configurable: false, - enumerable: false, - writable: false, - value: nullObject - }); - - return function (prototype, props) { - return create(prototype === null ? nullObject : prototype, props); - }; -}()); + case STAR: + if (!esutils.code.isWhiteSpace(ch)) { + result += String.fromCharCode(ch); + } + mode = esutils.code.isLineTerminator(ch) ? BEFORE_STAR : AFTER_STAR; + break; -},{"./set-prototype-of/is-implemented":47,"./set-prototype-of/shim":48}],36:[function(require,module,exports){ -"use strict"; + case AFTER_STAR: + result += String.fromCharCode(ch); + if (esutils.code.isLineTerminator(ch)) { + mode = BEFORE_STAR; + } + break; + } + index += 1; + } -module.exports = require("./_iterate")("forEach"); + return result.replace(/\s+$/, ''); + } -},{"./_iterate":30}],37:[function(require,module,exports){ -// Deprecated + // JSDoc Tag Parser -"use strict"; + (function (exports) { + var Rules, index, lineNumber, length, source, recoverable, sloppy, strict; -module.exports = function (obj) { - return typeof obj === "function"; -}; + function advance() { + var ch = source.charCodeAt(index); + index += 1; + if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(index) === 0x0A /* '\n' */)) { + lineNumber += 1; + } + return String.fromCharCode(ch); + } -},{}],38:[function(require,module,exports){ -"use strict"; + function scanTitle() { + var title = ''; + // waste '@' + advance(); -var isValue = require("./is-value"); + while (index < length && isASCIIAlphanumeric(source.charCodeAt(index))) { + title += advance(); + } -var map = { function: true, object: true }; + return title; + } -module.exports = function (value) { - return (isValue(value) && map[typeof value]) || false; -}; + function seekContent() { + var ch, + waiting, + last = index; -},{"./is-value":39}],39:[function(require,module,exports){ -"use strict"; + waiting = false; + while (last < length) { + ch = source.charCodeAt(last); + if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(last + 1) === 0x0A /* '\n' */)) { + waiting = true; + } else if (waiting) { + if (ch === 0x40 /* '@' */) { + break; + } + if (!esutils.code.isWhiteSpace(ch)) { + waiting = false; + } + } + last += 1; + } + return last; + } -var _undefined = require("../function/noop")(); // Support ES3 engines + // type expression may have nest brace, such as, + // { { ok: string } } + // + // therefore, scanning type expression with balancing braces. + function parseType(title, last) { + var ch, + brace, + type, + direct = false; -module.exports = function (val) { - return (val !== _undefined) && (val !== null); -}; + // search '{' + while (index < last) { + ch = source.charCodeAt(index); + if (esutils.code.isWhiteSpace(ch)) { + advance(); + } else if (ch === 0x7B /* '{' */) { + advance(); + break; + } else { + // this is direct pattern + direct = true; + break; + } + } -},{"../function/noop":21}],40:[function(require,module,exports){ -"use strict"; + if (direct) { + return null; + } -module.exports = require("./is-implemented")() - ? Object.keys - : require("./shim"); + // type expression { is found + brace = 1; + type = ''; + while (index < last) { + ch = source.charCodeAt(index); + if (esutils.code.isLineTerminator(ch)) { + advance(); + } else { + if (ch === 0x7D /* '}' */) { + brace -= 1; + if (brace === 0) { + advance(); + break; + } + } else if (ch === 0x7B /* '{' */) { + brace += 1; + } + type += advance(); + } + } -},{"./is-implemented":41,"./shim":42}],41:[function(require,module,exports){ -"use strict"; + if (brace !== 0) { + // braces is not balanced + return utility.throwError('Braces are not balanced'); + } -module.exports = function () { - try { - Object.keys("primitive"); - return true; - } catch (e) { - return false; -} -}; + if (isAllowedOptional(title)) { + return typed.parseParamType(type); + } -},{}],42:[function(require,module,exports){ -"use strict"; + return typed.parseType(type); + } -var isValue = require("../is-value"); + function scanIdentifier(last) { + var identifier; + if (!esutils.code.isIdentifierStartES5(source.charCodeAt(index))) { + return null; + } + identifier = advance(); + while (index < last && esutils.code.isIdentifierPartES5(source.charCodeAt(index))) { + identifier += advance(); + } + return identifier; + } -var keys = Object.keys; + function skipWhiteSpace(last) { + while (index < last && (esutils.code.isWhiteSpace(source.charCodeAt(index)) || esutils.code.isLineTerminator(source.charCodeAt(index)))) { + advance(); + } + } -module.exports = function (object) { - return keys(isValue(object) ? Object(object) : object); -}; + function parseName(last, allowBrackets, allowNestedParams) { + var name = '', + useBrackets, + insideString; -},{"../is-value":39}],43:[function(require,module,exports){ -"use strict"; + skipWhiteSpace(last); -var callable = require("./valid-callable") - , forEach = require("./for-each") - , call = Function.prototype.call; + if (index >= last) { + return null; + } -module.exports = function (obj, cb /*, thisArg*/) { - var result = {}, thisArg = arguments[2]; - callable(cb); - forEach(obj, function (value, key, targetObj, index) { - result[key] = call.call(cb, thisArg, value, key, targetObj, index); - }); - return result; -}; + if (allowBrackets && source.charCodeAt(index) === 0x5B /* '[' */) { + useBrackets = true; + name = advance(); + } -},{"./for-each":36,"./valid-callable":49}],44:[function(require,module,exports){ -"use strict"; + if (!esutils.code.isIdentifierStartES5(source.charCodeAt(index))) { + return null; + } -var isValue = require("./is-value"); + name += scanIdentifier(last); -var forEach = Array.prototype.forEach, create = Object.create; + if (allowNestedParams) { + if (source.charCodeAt(index) === 0x3A /* ':' */ && (name === 'module' || name === 'external' || name === 'event')) { + name += advance(); + name += scanIdentifier(last); + } + if (source.charCodeAt(index) === 0x5B /* '[' */ && source.charCodeAt(index + 1) === 0x5D /* ']' */) { + name += advance(); + name += advance(); + } + while (source.charCodeAt(index) === 0x2E /* '.' */ || source.charCodeAt(index) === 0x2F /* '/' */ || source.charCodeAt(index) === 0x23 /* '#' */ || source.charCodeAt(index) === 0x2D /* '-' */ || source.charCodeAt(index) === 0x7E /* '~' */) { + name += advance(); + name += scanIdentifier(last); + } + } -var process = function (src, obj) { - var key; - for (key in src) obj[key] = src[key]; -}; + if (useBrackets) { + skipWhiteSpace(last); + // do we have a default value for this? + if (source.charCodeAt(index) === 0x3D /* '=' */) { + // consume the '='' symbol + name += advance(); + skipWhiteSpace(last); -// eslint-disable-next-line no-unused-vars -module.exports = function (opts1 /*, …options*/) { - var result = create(null); - forEach.call(arguments, function (options) { - if (!isValue(options)) return; - process(Object(options), result); - }); - return result; -}; + var ch; + var bracketDepth = 1; -},{"./is-value":39}],45:[function(require,module,exports){ -"use strict"; + // scan in the default value + while (index < last) { + ch = source.charCodeAt(index); -var forEach = Array.prototype.forEach, create = Object.create; + if (esutils.code.isWhiteSpace(ch)) { + if (!insideString) { + skipWhiteSpace(last); + ch = source.charCodeAt(index); + } + } -// eslint-disable-next-line no-unused-vars -module.exports = function (arg /*, …args*/) { - var set = create(null); - forEach.call(arguments, function (name) { - set[name] = true; - }); - return set; -}; + if (ch === 0x27 /* ''' */) { + if (!insideString) { + insideString = '\''; + } else { + if (insideString === '\'') { + insideString = ''; + } + } + } -},{}],46:[function(require,module,exports){ -"use strict"; + if (ch === 0x22 /* '"' */) { + if (!insideString) { + insideString = '"'; + } else { + if (insideString === '"') { + insideString = ''; + } + } + } -module.exports = require("./is-implemented")() - ? Object.setPrototypeOf - : require("./shim"); + if (ch === 0x5B /* '[' */) { + bracketDepth++; + } else if (ch === 0x5D /* ']' */ && --bracketDepth === 0) { + break; + } -},{"./is-implemented":47,"./shim":48}],47:[function(require,module,exports){ -"use strict"; + name += advance(); + } + } -var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; + skipWhiteSpace(last); -module.exports = function (/* CustomCreate*/) { - var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create; - if (typeof setPrototypeOf !== "function") return false; - return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject; -}; + if (index >= last || source.charCodeAt(index) !== 0x5D /* ']' */) { + // we never found a closing ']' + return null; + } -},{}],48:[function(require,module,exports){ -/* eslint no-proto: "off" */ + // collect the last ']' + name += advance(); + } -// Big thanks to @WebReflection for sorting this out -// https://gist.github.com/WebReflection/5593554 + return name; + } -"use strict"; + function skipToTag() { + while (index < length && source.charCodeAt(index) !== 0x40 /* '@' */) { + advance(); + } + if (index >= length) { + return false; + } + utility.assert(source.charCodeAt(index) === 0x40 /* '@' */); + return true; + } -var isObject = require("../is-object") - , value = require("../valid-value") - , objIsPrototypOf = Object.prototype.isPrototypeOf - , defineProperty = Object.defineProperty - , nullDesc = { - configurable: true, - enumerable: false, - writable: true, - value: undefined -} - , validate; - -validate = function (obj, prototype) { - value(obj); - if (prototype === null || isObject(prototype)) return obj; - throw new TypeError("Prototype must be null or an object"); -}; - -module.exports = (function (status) { - var fn, set; - if (!status) return null; - if (status.level === 2) { - if (status.set) { - set = status.set; - fn = function (obj, prototype) { - set.call(validate(obj, prototype), prototype); - return obj; - }; - } else { - fn = function (obj, prototype) { - validate(obj, prototype).__proto__ = prototype; - return obj; - }; - } - } else { - fn = function self (obj, prototype) { - var isNullBase; - validate(obj, prototype); - isNullBase = objIsPrototypOf.call(self.nullPolyfill, obj); - if (isNullBase) delete self.nullPolyfill.__proto__; - if (prototype === null) prototype = self.nullPolyfill; - obj.__proto__ = prototype; - if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc); - return obj; - }; - } - return Object.defineProperty(fn, "level", { - configurable: false, - enumerable: false, - writable: false, - value: status.level - }); -}( - (function () { - var tmpObj1 = Object.create(null) - , tmpObj2 = {} - , set - , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"); - - if (desc) { - try { - set = desc.set; // Opera crashes at this point - set.call(tmpObj1, tmpObj2); - } catch (ignore) {} - if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 }; - } + function TagParser(options, title) { + this._options = options; + this._title = title.toLowerCase(); + this._tag = { + title: title, + description: null + }; + if (this._options.lineNumbers) { + this._tag.lineNumber = lineNumber; + } + this._last = 0; + // space to save special information for title parsers. + this._extra = {}; + } - tmpObj1.__proto__ = tmpObj2; - if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 }; + // addError(err, ...) + TagParser.prototype.addError = function addError(errorText) { + var args = Array.prototype.slice.call(arguments, 1), + msg = errorText.replace(/%(\d)/g, function (whole, index) { + utility.assert(index < args.length, 'Message reference must be in range'); + return args[index]; + }); - tmpObj1 = {}; - tmpObj1.__proto__ = tmpObj2; - if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 }; + if (!this._tag.errors) { + this._tag.errors = []; + } + if (strict) { + utility.throwError(msg); + } + this._tag.errors.push(msg); + return recoverable; + }; - return false; - })() -)); + TagParser.prototype.parseType = function () { + // type required titles + if (isTypeParameterRequired(this._title)) { + try { + this._tag.type = parseType(this._title, this._last); + if (!this._tag.type) { + if (!isParamTitle(this._title) && !isReturnTitle(this._title)) { + if (!this.addError('Missing or invalid tag type')) { + return false; + } + } + } + } catch (error) { + this._tag.type = null; + if (!this.addError(error.message)) { + return false; + } + } + } else if (isAllowedType(this._title)) { + // optional types + try { + this._tag.type = parseType(this._title, this._last); + } catch (e) { + //For optional types, lets drop the thrown error when we hit the end of the file + } + } + return true; + }; -require("../create"); + TagParser.prototype._parseNamePath = function (optional) { + var name; + name = parseName(this._last, sloppy && isAllowedOptional(this._title), true); + if (!name) { + if (!optional) { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } + this._tag.name = name; + return true; + }; -},{"../create":35,"../is-object":38,"../valid-value":51}],49:[function(require,module,exports){ -"use strict"; + TagParser.prototype.parseNamePath = function () { + return this._parseNamePath(false); + }; -module.exports = function (fn) { - if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); - return fn; -}; + TagParser.prototype.parseNamePathOptional = function () { + return this._parseNamePath(true); + }; -},{}],50:[function(require,module,exports){ -"use strict"; + TagParser.prototype.parseName = function () { + var assign, name; -var isObject = require("./is-object"); + // param, property requires name + if (isAllowedName(this._title)) { + this._tag.name = parseName(this._last, sloppy && isAllowedOptional(this._title), isAllowedNested(this._title)); + if (!this._tag.name) { + if (!isNameParameterRequired(this._title)) { + return true; + } -module.exports = function (value) { - if (!isObject(value)) throw new TypeError(value + " is not an Object"); - return value; -}; + // it's possible the name has already been parsed but interpreted as a type + // it's also possible this is a sloppy declaration, in which case it will be + // fixed at the end + if (isParamTitle(this._title) && this._tag.type && this._tag.type.name) { + this._extra.name = this._tag.type; + this._tag.name = this._tag.type.name; + this._tag.type = null; + } else { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } else { + name = this._tag.name; + if (name.charAt(0) === '[' && name.charAt(name.length - 1) === ']') { + // extract the default value if there is one + // example: @param {string} [somebody=John Doe] description + assign = name.substring(1, name.length - 1).split('='); + if (assign[1]) { + this._tag['default'] = assign[1]; + } + this._tag.name = assign[0]; -},{"./is-object":38}],51:[function(require,module,exports){ -"use strict"; + // convert to an optional type + if (this._tag.type && this._tag.type.type !== 'OptionalType') { + this._tag.type = { + type: 'OptionalType', + expression: this._tag.type + }; + } + } + } + } -var isValue = require("./is-value"); + return true; + }; -module.exports = function (value) { - if (!isValue(value)) throw new TypeError("Cannot use null or undefined"); - return value; -}; + TagParser.prototype.parseDescription = function parseDescription() { + var description = trim(sliceSource(source, index, this._last)); + if (description) { + if (/^-\s+/.test(description)) { + description = description.substring(2); + } + this._tag.description = description; + } + return true; + }; -},{"./is-value":39}],52:[function(require,module,exports){ -"use strict"; + TagParser.prototype.parseCaption = function parseDescription() { + var description = trim(sliceSource(source, index, this._last)); + var captionStartTag = ''; + var captionEndTag = ''; + var captionStart = description.indexOf(captionStartTag); + var captionEnd = description.indexOf(captionEndTag); + if (captionStart >= 0 && captionEnd >= 0) { + this._tag.caption = trim(description.substring(captionStart + captionStartTag.length, captionEnd)); + this._tag.description = trim(description.substring(captionEnd + captionEndTag.length)); + } else { + this._tag.description = description; + } + return true; + }; -module.exports = require("./is-implemented")() - ? String.prototype.contains - : require("./shim"); + TagParser.prototype.parseKind = function parseKind() { + var kind, kinds; + kinds = { + 'class': true, + 'constant': true, + 'event': true, + 'external': true, + 'file': true, + 'function': true, + 'member': true, + 'mixin': true, + 'module': true, + 'namespace': true, + 'typedef': true + }; + kind = trim(sliceSource(source, index, this._last)); + this._tag.kind = kind; + if (!hasOwnProperty(kinds, kind)) { + if (!this.addError('Invalid kind name \'%0\'', kind)) { + return false; + } + } + return true; + }; -},{"./is-implemented":53,"./shim":54}],53:[function(require,module,exports){ -"use strict"; + TagParser.prototype.parseAccess = function parseAccess() { + var access; + access = trim(sliceSource(source, index, this._last)); + this._tag.access = access; + if (access !== 'private' && access !== 'protected' && access !== 'public') { + if (!this.addError('Invalid access name \'%0\'', access)) { + return false; + } + } + return true; + }; -var str = "razdwatrzy"; + TagParser.prototype.parseThis = function parseAccess() { + // this name may be a name expression (e.g. {foo.bar}) + // or a name path (e.g. foo.bar) + var value = trim(sliceSource(source, index, this._last)); + if (value && value.charAt(0) === '{') { + var gotType = this.parseType(); + if (gotType && this._tag.type.type === 'NameExpression') { + this._tag.name = this._tag.type.name; + return true; + } else { + return this.addError('Invalid name for this'); + } + } else { + return this.parseNamePath(); + } + }; -module.exports = function () { - if (typeof str.contains !== "function") return false; - return (str.contains("dwa") === true) && (str.contains("foo") === false); -}; + TagParser.prototype.parseVariation = function parseVariation() { + var variation, text; + text = trim(sliceSource(source, index, this._last)); + variation = parseFloat(text, 10); + this._tag.variation = variation; + if (isNaN(variation)) { + if (!this.addError('Invalid variation \'%0\'', text)) { + return false; + } + } + return true; + }; -},{}],54:[function(require,module,exports){ -"use strict"; + TagParser.prototype.ensureEnd = function () { + var shouldBeEmpty = trim(sliceSource(source, index, this._last)); + if (shouldBeEmpty) { + if (!this.addError('Unknown content \'%0\'', shouldBeEmpty)) { + return false; + } + } + return true; + }; -var indexOf = String.prototype.indexOf; + TagParser.prototype.epilogue = function epilogue() { + var description; -module.exports = function (searchString/*, position*/) { - return indexOf.call(this, searchString, arguments[1]) > -1; -}; + description = this._tag.description; + // un-fix potentially sloppy declaration + if (isAllowedOptional(this._title) && !this._tag.type && description && description.charAt(0) === '[') { + this._tag.type = this._extra.name; + if (!this._tag.name) { + this._tag.name = undefined; + } -},{}],55:[function(require,module,exports){ -"use strict"; + if (!sloppy) { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } -var objToString = Object.prototype.toString, id = objToString.call(""); + return true; + }; -module.exports = function (value) { - return ( - typeof value === "string" || - (value && - typeof value === "object" && - (value instanceof String || objToString.call(value) === id)) || - false - ); -}; + Rules = { + // http://usejsdoc.org/tags-access.html + 'access': ['parseAccess'], + // http://usejsdoc.org/tags-alias.html + 'alias': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-augments.html + 'augments': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-constructor.html + 'constructor': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-constructor.html + 'class': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-extends.html + 'extends': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-example.html + 'example': ['parseCaption'], + // http://usejsdoc.org/tags-deprecated.html + 'deprecated': ['parseDescription'], + // http://usejsdoc.org/tags-global.html + 'global': ['ensureEnd'], + // http://usejsdoc.org/tags-inner.html + 'inner': ['ensureEnd'], + // http://usejsdoc.org/tags-instance.html + 'instance': ['ensureEnd'], + // http://usejsdoc.org/tags-kind.html + 'kind': ['parseKind'], + // http://usejsdoc.org/tags-mixes.html + 'mixes': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-mixin.html + 'mixin': ['parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-member.html + 'member': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-method.html + 'method': ['parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-module.html + 'module': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-method.html + 'func': ['parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-method.html + 'function': ['parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-member.html + 'var': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-name.html + 'name': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-namespace.html + 'namespace': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-private.html + 'private': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-protected.html + 'protected': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-public.html + 'public': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-readonly.html + 'readonly': ['ensureEnd'], + // http://usejsdoc.org/tags-requires.html + 'requires': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-since.html + 'since': ['parseDescription'], + // http://usejsdoc.org/tags-static.html + 'static': ['ensureEnd'], + // http://usejsdoc.org/tags-summary.html + 'summary': ['parseDescription'], + // http://usejsdoc.org/tags-this.html + 'this': ['parseThis', 'ensureEnd'], + // http://usejsdoc.org/tags-todo.html + 'todo': ['parseDescription'], + // http://usejsdoc.org/tags-typedef.html + 'typedef': ['parseType', 'parseNamePathOptional'], + // http://usejsdoc.org/tags-variation.html + 'variation': ['parseVariation'], + // http://usejsdoc.org/tags-version.html + 'version': ['parseDescription'] + }; -},{}],56:[function(require,module,exports){ -"use strict"; + TagParser.prototype.parse = function parse() { + var i, iz, sequences, method; -var generated = Object.create(null) + // empty title + if (!this._title) { + if (!this.addError('Missing or invalid title')) { + return null; + } + } - , random = Math.random; + // Seek to content last index. + this._last = seekContent(this._title); -module.exports = function () { - var str; - do { - str = random().toString(36).slice(2); -} while (generated[str]); - return str; -}; + if (hasOwnProperty(Rules, this._title)) { + sequences = Rules[this._title]; + } else { + // default sequences + sequences = ['parseType', 'parseName', 'parseDescription', 'epilogue']; + } -},{}],57:[function(require,module,exports){ -'use strict'; + for (i = 0, iz = sequences.length; i < iz; ++i) { + method = sequences[i]; + if (!this[method]()) { + return null; + } + } -var setPrototypeOf = require('es5-ext/object/set-prototype-of') - , contains = require('es5-ext/string/#/contains') - , d = require('d') - , Iterator = require('./') - - , defineProperty = Object.defineProperty - , ArrayIterator; - -ArrayIterator = module.exports = function (arr, kind) { - if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); - Iterator.call(this, arr); - if (!kind) kind = 'value'; - else if (contains.call(kind, 'key+value')) kind = 'key+value'; - else if (contains.call(kind, 'key')) kind = 'key'; - else kind = 'value'; - defineProperty(this, '__kind__', d('', kind)); -}; -if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); - -ArrayIterator.prototype = Object.create(Iterator.prototype, { - constructor: d(ArrayIterator), - _resolve: d(function (i) { - if (this.__kind__ === 'value') return this.__list__[i]; - if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; - return i; - }), - toString: d(function () { return '[object Array Iterator]'; }) -}); + return this._tag; + }; -},{"./":60,"d":7,"es5-ext/object/set-prototype-of":46,"es5-ext/string/#/contains":52}],58:[function(require,module,exports){ -'use strict'; + function parseTag(options) { + var title, parser, tag; -var isArguments = require('es5-ext/function/is-arguments') - , callable = require('es5-ext/object/valid-callable') - , isString = require('es5-ext/string/is-string') - , get = require('./get') - - , isArray = Array.isArray, call = Function.prototype.call - , some = Array.prototype.some; - -module.exports = function (iterable, cb/*, thisArg*/) { - var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code; - if (isArray(iterable) || isArguments(iterable)) mode = 'array'; - else if (isString(iterable)) mode = 'string'; - else iterable = get(iterable); - - callable(cb); - doBreak = function () { broken = true; }; - if (mode === 'array') { - some.call(iterable, function (value) { - call.call(cb, thisArg, value, doBreak); - if (broken) return true; - }); - return; - } - if (mode === 'string') { - l = iterable.length; - for (i = 0; i < l; ++i) { - char = iterable[i]; - if ((i + 1) < l) { - code = char.charCodeAt(0); - if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i]; - } - call.call(cb, thisArg, char, doBreak); - if (broken) break; - } - return; - } - result = iterable.next(); + // skip to tag + if (!skipToTag()) { + return null; + } - while (!result.done) { - call.call(cb, thisArg, result.value, doBreak); - if (broken) return; - result = iterable.next(); - } -}; + // scan title + title = scanTitle(); -},{"./get":59,"es5-ext/function/is-arguments":19,"es5-ext/object/valid-callable":49,"es5-ext/string/is-string":55}],59:[function(require,module,exports){ -'use strict'; + // construct tag parser + parser = new TagParser(options, title); + tag = parser.parse(); -var isArguments = require('es5-ext/function/is-arguments') - , isString = require('es5-ext/string/is-string') - , ArrayIterator = require('./array') - , StringIterator = require('./string') - , iterable = require('./valid-iterable') - , iteratorSymbol = require('es6-symbol').iterator; + // Seek global index to end of this tag. + while (index < parser._last) { + advance(); + } -module.exports = function (obj) { - if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); - if (isArguments(obj)) return new ArrayIterator(obj); - if (isString(obj)) return new StringIterator(obj); - return new ArrayIterator(obj); -}; + return tag; + } -},{"./array":57,"./string":62,"./valid-iterable":63,"es5-ext/function/is-arguments":19,"es5-ext/string/is-string":55,"es6-symbol":70}],60:[function(require,module,exports){ -'use strict'; + // + // Parse JSDoc + // -var clear = require('es5-ext/array/#/clear') - , assign = require('es5-ext/object/assign') - , callable = require('es5-ext/object/valid-callable') - , value = require('es5-ext/object/valid-value') - , d = require('d') - , autoBind = require('d/auto-bind') - , Symbol = require('es6-symbol') - - , defineProperty = Object.defineProperty - , defineProperties = Object.defineProperties - , Iterator; - -module.exports = Iterator = function (list, context) { - if (!(this instanceof Iterator)) return new Iterator(list, context); - defineProperties(this, { - __list__: d('w', value(list)), - __context__: d('w', context), - __nextIndex__: d('w', 0) - }); - if (!context) return; - callable(context.on); - context.on('_add', this._onAdd); - context.on('_delete', this._onDelete); - context.on('_clear', this._onClear); -}; - -defineProperties(Iterator.prototype, assign({ - constructor: d(Iterator), - _next: d(function () { - var i; - if (!this.__list__) return; - if (this.__redo__) { - i = this.__redo__.shift(); - if (i !== undefined) return i; - } - if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; - this._unBind(); - }), - next: d(function () { return this._createResult(this._next()); }), - _createResult: d(function (i) { - if (i === undefined) return { done: true, value: undefined }; - return { done: false, value: this._resolve(i) }; - }), - _resolve: d(function (i) { return this.__list__[i]; }), - _unBind: d(function () { - this.__list__ = null; - delete this.__redo__; - if (!this.__context__) return; - this.__context__.off('_add', this._onAdd); - this.__context__.off('_delete', this._onDelete); - this.__context__.off('_clear', this._onClear); - this.__context__ = null; - }), - toString: d(function () { return '[object Iterator]'; }) -}, autoBind({ - _onAdd: d(function (index) { - if (index >= this.__nextIndex__) return; - ++this.__nextIndex__; - if (!this.__redo__) { - defineProperty(this, '__redo__', d('c', [index])); - return; - } - this.__redo__.forEach(function (redo, i) { - if (redo >= index) this.__redo__[i] = ++redo; - }, this); - this.__redo__.push(index); - }), - _onDelete: d(function (index) { - var i; - if (index >= this.__nextIndex__) return; - --this.__nextIndex__; - if (!this.__redo__) return; - i = this.__redo__.indexOf(index); - if (i !== -1) this.__redo__.splice(i, 1); - this.__redo__.forEach(function (redo, i) { - if (redo > index) this.__redo__[i] = --redo; - }, this); - }), - _onClear: d(function () { - if (this.__redo__) clear.call(this.__redo__); - this.__nextIndex__ = 0; - }) -}))); + function scanJSDocDescription(preserveWhitespace) { + var description = '', + ch, + atAllowed; -defineProperty(Iterator.prototype, Symbol.iterator, d(function () { - return this; -})); -defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); + atAllowed = true; + while (index < length) { + ch = source.charCodeAt(index); -},{"d":7,"d/auto-bind":6,"es5-ext/array/#/clear":14,"es5-ext/object/assign":31,"es5-ext/object/valid-callable":49,"es5-ext/object/valid-value":51,"es6-symbol":70}],61:[function(require,module,exports){ -'use strict'; + if (atAllowed && ch === 0x40 /* '@' */) { + break; + } -var isArguments = require('es5-ext/function/is-arguments') - , isString = require('es5-ext/string/is-string') - , iteratorSymbol = require('es6-symbol').iterator + if (esutils.code.isLineTerminator(ch)) { + atAllowed = true; + } else if (atAllowed && !esutils.code.isWhiteSpace(ch)) { + atAllowed = false; + } - , isArray = Array.isArray; + description += advance(); + } -module.exports = function (value) { - if (value == null) return false; - if (isArray(value)) return true; - if (isString(value)) return true; - if (isArguments(value)) return true; - return (typeof value[iteratorSymbol] === 'function'); -}; + return preserveWhitespace ? description : trim(description); + } -},{"es5-ext/function/is-arguments":19,"es5-ext/string/is-string":55,"es6-symbol":70}],62:[function(require,module,exports){ -// Thanks @mathiasbynens -// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols + function parse(comment, options) { + var tags = [], + tag, + description, + interestingTags, + i, + iz; -'use strict'; + if (options === undefined) { + options = {}; + } -var setPrototypeOf = require('es5-ext/object/set-prototype-of') - , d = require('d') - , Iterator = require('./') - - , defineProperty = Object.defineProperty - , StringIterator; - -StringIterator = module.exports = function (str) { - if (!(this instanceof StringIterator)) return new StringIterator(str); - str = String(str); - Iterator.call(this, str); - defineProperty(this, '__length__', d('', str.length)); - -}; -if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); - -StringIterator.prototype = Object.create(Iterator.prototype, { - constructor: d(StringIterator), - _next: d(function () { - if (!this.__list__) return; - if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; - this._unBind(); - }), - _resolve: d(function (i) { - var char = this.__list__[i], code; - if (this.__nextIndex__ === this.__length__) return char; - code = char.charCodeAt(0); - if ((code >= 0xD800) && (code <= 0xDBFF)) return char + this.__list__[this.__nextIndex__++]; - return char; - }), - toString: d(function () { return '[object String Iterator]'; }) -}); + if (typeof options.unwrap === 'boolean' && options.unwrap) { + source = unwrapComment(comment); + } else { + source = comment; + } -},{"./":60,"d":7,"es5-ext/object/set-prototype-of":46}],63:[function(require,module,exports){ -'use strict'; + // array of relevant tags + if (options.tags) { + if (isArray(options.tags)) { + interestingTags = {}; + for (i = 0, iz = options.tags.length; i < iz; i++) { + if (typeof options.tags[i] === 'string') { + interestingTags[options.tags[i]] = true; + } else { + utility.throwError('Invalid "tags" parameter: ' + options.tags); + } + } + } else { + utility.throwError('Invalid "tags" parameter: ' + options.tags); + } + } + + length = source.length; + index = 0; + lineNumber = 0; + recoverable = options.recoverable; + sloppy = options.sloppy; + strict = options.strict; -var isIterable = require('./is-iterable'); + description = scanJSDocDescription(options.preserveWhitespace); -module.exports = function (value) { - if (!isIterable(value)) throw new TypeError(value + " is not iterable"); - return value; -}; + while (true) { + tag = parseTag(options); + if (!tag) { + break; + } + if (!interestingTags || interestingTags.hasOwnProperty(tag.title)) { + tags.push(tag); + } + } -},{"./is-iterable":61}],64:[function(require,module,exports){ -'use strict'; + return { + description: description, + tags: tags + }; + } + exports.parse = parse; + })(jsdoc = {}); -module.exports = require('./is-implemented')() ? Map : require('./polyfill'); + exports.version = utility.VERSION; + exports.parse = jsdoc.parse; + exports.parseType = typed.parseType; + exports.parseParamType = typed.parseParamType; + exports.unwrapComment = unwrapComment; + exports.Syntax = shallowCopy(typed.Syntax); + exports.Error = utility.DoctrineError; + exports.type = { + Syntax: exports.Syntax, + parseType: typed.parseType, + parseParamType: typed.parseParamType, + stringify: typed.stringify + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ -},{"./is-implemented":65,"./polyfill":69}],65:[function(require,module,exports){ +},{"./typed":55,"./utility":56,"esutils":76,"isarray":83}],55:[function(require,module,exports){ 'use strict'; -module.exports = function () { - var map, iterator, result; - if (typeof Map !== 'function') return false; - try { - // WebKit doesn't support arguments and crashes - map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); - } catch (e) { - return false; - } - if (String(map) !== '[object Map]') return false; - if (map.size !== 3) return false; - if (typeof map.clear !== 'function') return false; - if (typeof map.delete !== 'function') return false; - if (typeof map.entries !== 'function') return false; - if (typeof map.forEach !== 'function') return false; - if (typeof map.get !== 'function') return false; - if (typeof map.has !== 'function') return false; - if (typeof map.keys !== 'function') return false; - if (typeof map.set !== 'function') return false; - if (typeof map.values !== 'function') return false; - - iterator = map.entries(); - result = iterator.next(); - if (result.done !== false) return false; - if (!result.value) return false; - if (result.value[0] !== 'raz') return false; - if (result.value[1] !== 'one') return false; - - return true; -}; +/* + * @fileoverview Type expression parser. + * @author Yusuke Suzuki + * @author Dan Tao + * @author Andrew Eisenberg + */ -},{}],66:[function(require,module,exports){ -// Exports true if environment provides native `Map` implementation, -// whatever that is. +// "typed", the Type Expression Parser for doctrine. -'use strict'; +(function () { + 'use strict'; -module.exports = (function () { - if (typeof Map === 'undefined') return false; - return (Object.prototype.toString.call(new Map()) === '[object Map]'); -}()); + var Syntax, Token, source, length, index, previous, token, value, esutils, utility; -},{}],67:[function(require,module,exports){ -'use strict'; + esutils = require('esutils'); + utility = require('./utility'); -module.exports = require('es5-ext/object/primitive-set')('key', - 'value', 'key+value'); + Syntax = { + NullableLiteral: 'NullableLiteral', + AllLiteral: 'AllLiteral', + NullLiteral: 'NullLiteral', + UndefinedLiteral: 'UndefinedLiteral', + VoidLiteral: 'VoidLiteral', + UnionType: 'UnionType', + ArrayType: 'ArrayType', + RecordType: 'RecordType', + FieldType: 'FieldType', + FunctionType: 'FunctionType', + ParameterType: 'ParameterType', + RestType: 'RestType', + NonNullableType: 'NonNullableType', + OptionalType: 'OptionalType', + NullableType: 'NullableType', + NameExpression: 'NameExpression', + TypeApplication: 'TypeApplication', + StringLiteralType: 'StringLiteralType', + NumericLiteralType: 'NumericLiteralType', + BooleanLiteralType: 'BooleanLiteralType' + }; -},{"es5-ext/object/primitive-set":45}],68:[function(require,module,exports){ -'use strict'; + Token = { + ILLEGAL: 0, // ILLEGAL + DOT_LT: 1, // .< + REST: 2, // ... + LT: 3, // < + GT: 4, // > + LPAREN: 5, // ( + RPAREN: 6, // ) + LBRACE: 7, // { + RBRACE: 8, // } + LBRACK: 9, // [ + RBRACK: 10, // ] + COMMA: 11, // , + COLON: 12, // : + STAR: 13, // * + PIPE: 14, // | + QUESTION: 15, // ? + BANG: 16, // ! + EQUAL: 17, // = + NAME: 18, // name token + STRING: 19, // string + NUMBER: 20, // number + EOF: 21 + }; -var setPrototypeOf = require('es5-ext/object/set-prototype-of') - , d = require('d') - , Iterator = require('es6-iterator') - , toStringTagSymbol = require('es6-symbol').toStringTag - , kinds = require('./iterator-kinds') - - , defineProperties = Object.defineProperties - , unBind = Iterator.prototype._unBind - , MapIterator; - -MapIterator = module.exports = function (map, kind) { - if (!(this instanceof MapIterator)) return new MapIterator(map, kind); - Iterator.call(this, map.__mapKeysData__, map); - if (!kind || !kinds[kind]) kind = 'key+value'; - defineProperties(this, { - __kind__: d('', kind), - __values__: d('w', map.__mapValuesData__) - }); -}; -if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); - -MapIterator.prototype = Object.create(Iterator.prototype, { - constructor: d(MapIterator), - _resolve: d(function (i) { - if (this.__kind__ === 'value') return this.__values__[i]; - if (this.__kind__ === 'key') return this.__list__[i]; - return [this.__list__[i], this.__values__[i]]; - }), - _unBind: d(function () { - this.__values__ = null; - unBind.call(this); - }), - toString: d(function () { return '[object Map Iterator]'; }) -}); -Object.defineProperty(MapIterator.prototype, toStringTagSymbol, - d('c', 'Map Iterator')); + function isTypeName(ch) { + return '><(){}[],:*|?!='.indexOf(String.fromCharCode(ch)) === -1 && !esutils.code.isWhiteSpace(ch) && !esutils.code.isLineTerminator(ch); + } -},{"./iterator-kinds":67,"d":7,"es5-ext/object/set-prototype-of":46,"es6-iterator":60,"es6-symbol":70}],69:[function(require,module,exports){ -'use strict'; + function Context(previous, index, token, value) { + this._previous = previous; + this._index = index; + this._token = token; + this._value = value; + } -var clear = require('es5-ext/array/#/clear') - , eIndexOf = require('es5-ext/array/#/e-index-of') - , setPrototypeOf = require('es5-ext/object/set-prototype-of') - , callable = require('es5-ext/object/valid-callable') - , validValue = require('es5-ext/object/valid-value') - , d = require('d') - , ee = require('event-emitter') - , Symbol = require('es6-symbol') - , iterator = require('es6-iterator/valid-iterable') - , forOf = require('es6-iterator/for-of') - , Iterator = require('./lib/iterator') - , isNative = require('./is-native-implemented') - - , call = Function.prototype.call - , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf - , MapPoly; - -module.exports = MapPoly = function (/*iterable*/) { - var iterable = arguments[0], keys, values, self; - if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\''); - if (isNative && setPrototypeOf && (Map !== MapPoly)) { - self = setPrototypeOf(new Map(), getPrototypeOf(this)); - } else { - self = this; - } - if (iterable != null) iterator(iterable); - defineProperties(self, { - __mapKeysData__: d('c', keys = []), - __mapValuesData__: d('c', values = []) - }); - if (!iterable) return self; - forOf(iterable, function (value) { - var key = validValue(value)[0]; - value = value[1]; - if (eIndexOf.call(keys, key) !== -1) return; - keys.push(key); - values.push(value); - }, self); - return self; -}; - -if (isNative) { - if (setPrototypeOf) setPrototypeOf(MapPoly, Map); - MapPoly.prototype = Object.create(Map.prototype, { - constructor: d(MapPoly) - }); -} - -ee(defineProperties(MapPoly.prototype, { - clear: d(function () { - if (!this.__mapKeysData__.length) return; - clear.call(this.__mapKeysData__); - clear.call(this.__mapValuesData__); - this.emit('_clear'); - }), - delete: d(function (key) { - var index = eIndexOf.call(this.__mapKeysData__, key); - if (index === -1) return false; - this.__mapKeysData__.splice(index, 1); - this.__mapValuesData__.splice(index, 1); - this.emit('_delete', index, key); - return true; - }), - entries: d(function () { return new Iterator(this, 'key+value'); }), - forEach: d(function (cb/*, thisArg*/) { - var thisArg = arguments[1], iterator, result; - callable(cb); - iterator = this.entries(); - result = iterator._next(); - while (result !== undefined) { - call.call(cb, thisArg, this.__mapValuesData__[result], - this.__mapKeysData__[result], this); - result = iterator._next(); - } - }), - get: d(function (key) { - var index = eIndexOf.call(this.__mapKeysData__, key); - if (index === -1) return; - return this.__mapValuesData__[index]; - }), - has: d(function (key) { - return (eIndexOf.call(this.__mapKeysData__, key) !== -1); - }), - keys: d(function () { return new Iterator(this, 'key'); }), - set: d(function (key, value) { - var index = eIndexOf.call(this.__mapKeysData__, key), emit; - if (index === -1) { - index = this.__mapKeysData__.push(key) - 1; - emit = true; - } - this.__mapValuesData__[index] = value; - if (emit) this.emit('_add', index, key); - return this; - }), - size: d.gs(function () { return this.__mapKeysData__.length; }), - values: d(function () { return new Iterator(this, 'value'); }), - toString: d(function () { return '[object Map]'; }) -})); -Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { - return this.entries(); -})); -Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map')); - -},{"./is-native-implemented":66,"./lib/iterator":68,"d":7,"es5-ext/array/#/clear":14,"es5-ext/array/#/e-index-of":15,"es5-ext/object/set-prototype-of":46,"es5-ext/object/valid-callable":49,"es5-ext/object/valid-value":51,"es6-iterator/for-of":58,"es6-iterator/valid-iterable":63,"es6-symbol":70,"event-emitter":98}],70:[function(require,module,exports){ -'use strict'; + Context.prototype.restore = function () { + previous = this._previous; + index = this._index; + token = this._token; + value = this._value; + }; -module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); + Context.save = function () { + return new Context(previous, index, token, value); + }; -},{"./is-implemented":71,"./polyfill":73}],71:[function(require,module,exports){ -'use strict'; + function advance() { + var ch = source.charAt(index); + index += 1; + return ch; + } -var validTypes = { object: true, symbol: true }; + function scanHexEscape(prefix) { + var i, + len, + ch, + code = 0; -module.exports = function () { - var symbol; - if (typeof Symbol !== 'function') return false; - symbol = Symbol('test symbol'); - try { String(symbol); } catch (e) { return false; } + len = prefix === 'u' ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && esutils.code.isHexDigit(source.charCodeAt(index))) { + ch = advance(); + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } - // Return 'true' also for polyfills - if (!validTypes[typeof Symbol.iterator]) return false; - if (!validTypes[typeof Symbol.toPrimitive]) return false; - if (!validTypes[typeof Symbol.toStringTag]) return false; + function scanString() { + var str = '', + quote, + ch, + code, + unescaped, + restore; //TODO review removal octal = false + quote = source.charAt(index); + ++index; - return true; -}; + while (index < length) { + ch = advance(); -},{}],72:[function(require,module,exports){ -'use strict'; + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = advance(); + if (!esutils.code.isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'u': + case 'x': + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\v'; + break; -module.exports = function (x) { - if (!x) return false; - if (typeof x === 'symbol') return true; - if (!x.constructor) return false; - if (x.constructor.name !== 'Symbol') return false; - return (x[x.constructor.toStringTag] === 'Symbol'); -}; + default: + if (esutils.code.isOctalDigit(ch.charCodeAt(0))) { + code = '01234567'.indexOf(ch); -},{}],73:[function(require,module,exports){ -// ES2015 Symbol polyfill for environments that do not (or partially) support it + // \0 is not octal escape sequence + // Deprecating unused code. TODO review removal + //if (code !== 0) { + // octal = true; + //} -'use strict'; + if (index < length && esutils.code.isOctalDigit(source.charCodeAt(index))) { + //TODO Review Removal octal = true; + code = code * 8 + '01234567'.indexOf(advance()); -var d = require('d') - , validateSymbol = require('./validate-symbol') + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && index < length && esutils.code.isOctalDigit(source.charCodeAt(index))) { + code = code * 8 + '01234567'.indexOf(advance()); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + if (ch === '\r' && source.charCodeAt(index) === 0x0A /* '\n' */) { + ++index; + } + } + } else if (esutils.code.isLineTerminator(ch.charCodeAt(0))) { + break; + } else { + str += ch; + } + } - , create = Object.create, defineProperties = Object.defineProperties - , defineProperty = Object.defineProperty, objPrototype = Object.prototype - , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null) - , isNativeSafe; + if (quote !== '') { + utility.throwError('unexpected quote'); + } -if (typeof Symbol === 'function') { - NativeSymbol = Symbol; - try { - String(NativeSymbol()); - isNativeSafe = true; - } catch (ignore) {} -} - -var generateName = (function () { - var created = create(null); - return function (desc) { - var postfix = 0, name, ie11BugWorkaround; - while (created[desc + (postfix || '')]) ++postfix; - desc += (postfix || ''); - created[desc] = true; - name = '@@' + desc; - defineProperty(objPrototype, name, d.gs(null, function (value) { - // For IE11 issue see: - // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ - // ie11-broken-getters-on-dom-objects - // https://github.com/medikoo/es6-symbol/issues/12 - if (ie11BugWorkaround) return; - ie11BugWorkaround = true; - defineProperty(this, name, d(value)); - ie11BugWorkaround = false; - })); - return name; - }; -}()); - -// Internal constructor (not one exposed) for creating Symbol instances. -// This one is used to ensure that `someSymbol instanceof Symbol` always return false -HiddenSymbol = function Symbol(description) { - if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor'); - return SymbolPolyfill(description); -}; - -// Exposed `Symbol` constructor -// (returns instances of HiddenSymbol) -module.exports = SymbolPolyfill = function Symbol(description) { - var symbol; - if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor'); - if (isNativeSafe) return NativeSymbol(description); - symbol = create(HiddenSymbol.prototype); - description = (description === undefined ? '' : String(description)); - return defineProperties(symbol, { - __description__: d('', description), - __name__: d('', generateName(description)) - }); -}; -defineProperties(SymbolPolyfill, { - for: d(function (key) { - if (globalSymbols[key]) return globalSymbols[key]; - return (globalSymbols[key] = SymbolPolyfill(String(key))); - }), - keyFor: d(function (s) { - var key; - validateSymbol(s); - for (key in globalSymbols) if (globalSymbols[key] === s) return key; - }), - - // To ensure proper interoperability with other native functions (e.g. Array.from) - // fallback to eventual native implementation of given symbol - hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')), - isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) || - SymbolPolyfill('isConcatSpreadable')), - iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')), - match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')), - replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')), - search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')), - species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')), - split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')), - toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')), - toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')), - unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables')) -}); - -// Internal tweaks for real symbol producer -defineProperties(HiddenSymbol.prototype, { - constructor: d(SymbolPolyfill), - toString: d('', function () { return this.__name__; }) -}); - -// Proper implementation of methods exposed on Symbol.prototype -// They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype -defineProperties(SymbolPolyfill.prototype, { - toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), - valueOf: d(function () { return validateSymbol(this); }) -}); -defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () { - var symbol = validateSymbol(this); - if (typeof symbol === 'symbol') return symbol; - return symbol.toString(); -})); -defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol')); - -// Proper implementaton of toPrimitive and toStringTag for returned symbol instances -defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, - d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])); - -// Note: It's important to define `toPrimitive` as last one, as some implementations -// implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) -// And that may invoke error in definition flow: -// See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 -defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, - d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])); - -},{"./validate-symbol":74,"d":7}],74:[function(require,module,exports){ -'use strict'; - -var isSymbol = require('./is-symbol'); - -module.exports = function (value) { - if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); - return value; -}; - -},{"./is-symbol":72}],75:[function(require,module,exports){ -'use strict'; - -module.exports = require('./is-implemented')() ? WeakMap : require('./polyfill'); - -},{"./is-implemented":76,"./polyfill":78}],76:[function(require,module,exports){ -'use strict'; - -module.exports = function () { - var weakMap, x; - if (typeof WeakMap !== 'function') return false; - try { - // WebKit doesn't support arguments and crashes - weakMap = new WeakMap([[x = {}, 'one'], [{}, 'two'], [{}, 'three']]); - } catch (e) { - return false; - } - if (String(weakMap) !== '[object WeakMap]') return false; - if (typeof weakMap.set !== 'function') return false; - if (weakMap.set({}, 1) !== weakMap) return false; - if (typeof weakMap.delete !== 'function') return false; - if (typeof weakMap.has !== 'function') return false; - if (weakMap.get(x) !== 'one') return false; - - return true; -}; - -},{}],77:[function(require,module,exports){ -// Exports true if environment provides native `WeakMap` implementation, whatever that is. - -'use strict'; - -module.exports = (function () { - if (typeof WeakMap !== 'function') return false; - return (Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'); -}()); - -},{}],78:[function(require,module,exports){ -'use strict'; - -var setPrototypeOf = require('es5-ext/object/set-prototype-of') - , object = require('es5-ext/object/valid-object') - , value = require('es5-ext/object/valid-value') - , randomUniq = require('es5-ext/string/random-uniq') - , d = require('d') - , getIterator = require('es6-iterator/get') - , forOf = require('es6-iterator/for-of') - , toStringTagSymbol = require('es6-symbol').toStringTag - , isNative = require('./is-native-implemented') - - , isArray = Array.isArray, defineProperty = Object.defineProperty - , hasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf - , WeakMapPoly; - -module.exports = WeakMapPoly = function (/*iterable*/) { - var iterable = arguments[0], self; - if (!(this instanceof WeakMapPoly)) throw new TypeError('Constructor requires \'new\''); - if (isNative && setPrototypeOf && (WeakMap !== WeakMapPoly)) { - self = setPrototypeOf(new WeakMap(), getPrototypeOf(this)); - } else { - self = this; - } - if (iterable != null) { - if (!isArray(iterable)) iterable = getIterator(iterable); - } - defineProperty(self, '__weakMapData__', d('c', '$weakMap$' + randomUniq())); - if (!iterable) return self; - forOf(iterable, function (val) { - value(val); - self.set(val[0], val[1]); - }); - return self; -}; - -if (isNative) { - if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap); - WeakMapPoly.prototype = Object.create(WeakMap.prototype, { - constructor: d(WeakMapPoly) - }); -} - -Object.defineProperties(WeakMapPoly.prototype, { - delete: d(function (key) { - if (hasOwnProperty.call(object(key), this.__weakMapData__)) { - delete key[this.__weakMapData__]; - return true; - } - return false; - }), - get: d(function (key) { - if (hasOwnProperty.call(object(key), this.__weakMapData__)) { - return key[this.__weakMapData__]; - } - }), - has: d(function (key) { - return hasOwnProperty.call(object(key), this.__weakMapData__); - }), - set: d(function (key, value) { - defineProperty(object(key), this.__weakMapData__, d('c', value)); - return this; - }), - toString: d(function () { return '[object WeakMap]'; }) -}); -defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap')); + value = str; + return Token.STRING; + } -},{"./is-native-implemented":77,"d":7,"es5-ext/object/set-prototype-of":46,"es5-ext/object/valid-object":50,"es5-ext/object/valid-value":51,"es5-ext/string/random-uniq":56,"es6-iterator/for-of":58,"es6-iterator/get":59,"es6-symbol":70}],79:[function(require,module,exports){ -'use strict'; + function scanNumber() { + var number, ch; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Definition = exports.ParameterDefinition = undefined; + number = ''; + ch = source.charCodeAt(index); -var _variable = require('./variable'); + if (ch !== 0x2E /* '.' */) { + number = advance(); + ch = source.charCodeAt(index); -var _variable2 = _interopRequireDefault(_variable); + if (number === '0') { + if (ch === 0x78 /* 'x' */ || ch === 0x58 /* 'X' */) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isHexDigit(ch)) { + break; + } + number += advance(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (number.length <= 2) { + // only 0x + utility.throwError('unexpected token'); + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + if (index < length) { + ch = source.charCodeAt(index); + if (esutils.code.isIdentifierStartES5(ch)) { + utility.throwError('unexpected token'); + } + } + value = parseInt(number, 16); + return Token.NUMBER; + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + if (esutils.code.isOctalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isOctalDigit(ch)) { + break; + } + number += advance(); + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /* - Copyright (C) 2015 Yusuke Suzuki - - 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 BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ + if (index < length) { + ch = source.charCodeAt(index); + if (esutils.code.isIdentifierStartES5(ch) || esutils.code.isDecimalDigit(ch)) { + utility.throwError('unexpected token'); + } + } + value = parseInt(number, 8); + return Token.NUMBER; + } -/** - * @class Definition - */ + if (esutils.code.isDecimalDigit(ch)) { + utility.throwError('unexpected token'); + } + } -var Definition = function Definition(type, name, node, parent, index, kind) { - _classCallCheck(this, Definition); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } - /** - * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). - */ - this.type = type; - /** - * @member {esprima.Identifier} Definition#name - the identifier AST node of the occurrence. - */ - this.name = name; - /** - * @member {esprima.Node} Definition#node - the enclosing node of the identifier. - */ - this.node = node; - /** - * @member {esprima.Node?} Definition#parent - the enclosing statement node of the identifier. - */ - this.parent = parent; - /** - * @member {Number?} Definition#index - the index in the declaration statement. - */ - this.index = index; - /** - * @member {String?} Definition#kind - the kind of the declaration statement. - */ - this.kind = kind; -}; + if (ch === 0x2E /* '.' */) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } -/** - * @class ParameterDefinition - */ + if (ch === 0x65 /* 'e' */ || ch === 0x45 /* 'E' */) { + number += advance(); + ch = source.charCodeAt(index); + if (ch === 0x2B /* '+' */ || ch === 0x2D /* '-' */) { + number += advance(); + } -exports.default = Definition; + ch = source.charCodeAt(index); + if (esutils.code.isDecimalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } else { + utility.throwError('unexpected token'); + } + } -var ParameterDefinition = function (_Definition) { - _inherits(ParameterDefinition, _Definition); + if (index < length) { + ch = source.charCodeAt(index); + if (esutils.code.isIdentifierStartES5(ch)) { + utility.throwError('unexpected token'); + } + } - function ParameterDefinition(name, node, index, rest) { - _classCallCheck(this, ParameterDefinition); + value = parseFloat(number); + return Token.NUMBER; + } - /** - * Whether the parameter definition is a part of a rest parameter. - * @member {boolean} ParameterDefinition#rest - */ + function scanTypeName() { + var ch, ch2; - var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ParameterDefinition).call(this, _variable2.default.Parameter, name, node, null, index, null)); + value = advance(); + while (index < length && isTypeName(source.charCodeAt(index))) { + ch = source.charCodeAt(index); + if (ch === 0x2E /* '.' */) { + if (index + 1 >= length) { + return Token.ILLEGAL; + } + ch2 = source.charCodeAt(index + 1); + if (ch2 === 0x3C /* '<' */) { + break; + } + } + value += advance(); + } + return Token.NAME; + } - _this.rest = rest; - return _this; - } + function next() { + var ch; - return ParameterDefinition; -}(Definition); + previous = index; -exports.ParameterDefinition = ParameterDefinition; -exports.Definition = Definition; + while (index < length && esutils.code.isWhiteSpace(source.charCodeAt(index))) { + advance(); + } + if (index >= length) { + token = Token.EOF; + return token; + } -/* vim: set sw=4 ts=4 et tw=80 : */ + ch = source.charCodeAt(index); + switch (ch) { + case 0x27: /* ''' */ + case 0x22: + /* '"' */ + token = scanString(); + return token; + case 0x3A: + /* ':' */ + advance(); + token = Token.COLON; + return token; -},{"./variable":86}],80:[function(require,module,exports){ -'use strict'; + case 0x2C: + /* ',' */ + advance(); + token = Token.COMMA; + return token; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.ScopeManager = exports.Scope = exports.Variable = exports.Reference = exports.version = undefined; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /* - Copyright (C) 2012-2014 Yusuke Suzuki - Copyright (C) 2013 Alex Seville - Copyright (C) 2014 Thiago de Arruda - - 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 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. - */ + case 0x28: + /* '(' */ + advance(); + token = Token.LPAREN; + return token; -/** - * Escope (escope) is an ECMAScript - * scope analyzer extracted from the esmangle project. - *

- * escope finds lexical scopes in a source program, i.e. areas of that - * program where different occurrences of the same identifier refer to the same - * variable. With each scope the contained variables are collected, and each - * identifier reference in code is linked to its corresponding variable (if - * possible). - *

- * escope works on a syntax tree of the parsed source code which has - * to adhere to the - * Mozilla Parser API. E.g. esprima is a parser - * that produces such syntax trees. - *

- * The main interface is the {@link analyze} function. - * @module escope - */ + case 0x29: + /* ')' */ + advance(); + token = Token.RPAREN; + return token; -/*jslint bitwise:true */ + case 0x5B: + /* '[' */ + advance(); + token = Token.LBRACK; + return token; -exports.analyze = analyze; + case 0x5D: + /* ']' */ + advance(); + token = Token.RBRACK; + return token; -var _assert = require('assert'); + case 0x7B: + /* '{' */ + advance(); + token = Token.LBRACE; + return token; -var _assert2 = _interopRequireDefault(_assert); + case 0x7D: + /* '}' */ + advance(); + token = Token.RBRACE; + return token; -var _scopeManager = require('./scope-manager'); + case 0x2E: + /* '.' */ + if (index + 1 < length) { + ch = source.charCodeAt(index + 1); + if (ch === 0x3C /* '<' */) { + advance(); // '.' + advance(); // '<' + token = Token.DOT_LT; + return token; + } -var _scopeManager2 = _interopRequireDefault(_scopeManager); + if (ch === 0x2E /* '.' */ && index + 2 < length && source.charCodeAt(index + 2) === 0x2E /* '.' */) { + advance(); // '.' + advance(); // '.' + advance(); // '.' + token = Token.REST; + return token; + } -var _referencer = require('./referencer'); + if (esutils.code.isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } + } + token = Token.ILLEGAL; + return token; -var _referencer2 = _interopRequireDefault(_referencer); + case 0x3C: + /* '<' */ + advance(); + token = Token.LT; + return token; -var _reference = require('./reference'); + case 0x3E: + /* '>' */ + advance(); + token = Token.GT; + return token; -var _reference2 = _interopRequireDefault(_reference); + case 0x2A: + /* '*' */ + advance(); + token = Token.STAR; + return token; -var _variable = require('./variable'); + case 0x7C: + /* '|' */ + advance(); + token = Token.PIPE; + return token; -var _variable2 = _interopRequireDefault(_variable); + case 0x3F: + /* '?' */ + advance(); + token = Token.QUESTION; + return token; -var _scope = require('./scope'); + case 0x21: + /* '!' */ + advance(); + token = Token.BANG; + return token; -var _scope2 = _interopRequireDefault(_scope); + case 0x3D: + /* '=' */ + advance(); + token = Token.EQUAL; + return token; -var _package = require('../package.json'); + case 0x2D: + /* '-' */ + token = scanNumber(); + return token; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + default: + if (esutils.code.isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } -function defaultOptions() { - return { - optimistic: false, - directive: false, - nodejsScope: false, - impliedStrict: false, - sourceType: 'script', // one of ['script', 'module'] - ecmaVersion: 5, - childVisitorKeys: null, - fallback: 'iteration' - }; -} + // type string permits following case, + // + // namespace.module.MyClass + // + // this reduced 1 token TK_NAME + utility.assert(isTypeName(ch)); + token = scanTypeName(); + return token; + } + } -function updateDeeply(target, override) { - var key, val; + function consume(target, text) { + utility.assert(token === target, text || 'consumed token not matched'); + next(); + } - function isHashObject(target) { - return (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target instanceof Object && !(target instanceof Array) && !(target instanceof RegExp); + function expect(target, message) { + if (token !== target) { + utility.throwError(message || 'unexpected token'); + } + next(); } - for (key in override) { - if (override.hasOwnProperty(key)) { - val = override[key]; - if (isHashObject(val)) { - if (isHashObject(target[key])) { - updateDeeply(target[key], val); - } else { - target[key] = updateDeeply({}, val); + // UnionType := '(' TypeUnionList ')' + // + // TypeUnionList := + // <> + // | NonemptyTypeUnionList + // + // NonemptyTypeUnionList := + // TypeExpression + // | TypeExpression '|' NonemptyTypeUnionList + function parseUnionType() { + var elements; + consume(Token.LPAREN, 'UnionType should start with ('); + elements = []; + if (token !== Token.RPAREN) { + while (true) { + elements.push(parseTypeExpression()); + if (token === Token.RPAREN) { + break; } - } else { - target[key] = val; + expect(Token.PIPE); } } + consume(Token.RPAREN, 'UnionType should end with )'); + return { + type: Syntax.UnionType, + elements: elements + }; } - return target; -} - -/** - * Main interface function. Takes an Esprima syntax tree and returns the - * analyzed scopes. - * @function analyze - * @param {esprima.Tree} tree - * @param {Object} providedOptions - Options that tailor the scope analysis - * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag - * @param {boolean} [providedOptions.directive=false]- the directive flag - * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls - * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole - * script is executed under node.js environment. When enabled, escope adds - * a function scope immediately following the global scope. - * @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode - * (if ecmaVersion >= 5). - * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module' - * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered - * @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. - * @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. - * @return {ScopeManager} - */ -function analyze(tree, providedOptions) { - var scopeManager, referencer, options; - - options = updateDeeply(defaultOptions(), providedOptions); - - scopeManager = new _scopeManager2.default(options); - - referencer = new _referencer2.default(options, scopeManager); - referencer.visit(tree); - - (0, _assert2.default)(scopeManager.__currentScope === null, 'currentScope should be null.'); - - return scopeManager; -} - -exports. -/** @name module:escope.version */ -version = _package.version; -exports. -/** @name module:escope.Reference */ -Reference = _reference2.default; -exports. -/** @name module:escope.Variable */ -Variable = _variable2.default; -exports. -/** @name module:escope.Scope */ -Scope = _scope2.default; -exports. -/** @name module:escope.ScopeManager */ -ScopeManager = _scopeManager2.default; - -/* vim: set sw=4 ts=4 et tw=80 : */ - -},{"../package.json":87,"./reference":82,"./referencer":83,"./scope":85,"./scope-manager":84,"./variable":86,"assert":5}],81:[function(require,module,exports){ -'use strict'; + // ArrayType := '[' ElementTypeList ']' + // + // ElementTypeList := + // <> + // | TypeExpression + // | '...' TypeExpression + // | TypeExpression ',' ElementTypeList + function parseArrayType() { + var elements; + consume(Token.LBRACK, 'ArrayType should start with ['); + elements = []; + while (token !== Token.RBRACK) { + if (token === Token.REST) { + consume(Token.REST); + elements.push({ + type: Syntax.RestType, + expression: parseTypeExpression() + }); + break; + } else { + elements.push(parseTypeExpression()); + } + if (token !== Token.RBRACK) { + expect(Token.COMMA); + } + } + expect(Token.RBRACK); + return { + type: Syntax.ArrayType, + elements: elements + }; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + function parseFieldName() { + var v = value; + if (token === Token.NAME || token === Token.STRING) { + next(); + return v; + } -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + if (token === Token.NUMBER) { + consume(Token.NUMBER); + return String(v); + } -var _estraverse = require('estraverse'); + utility.throwError('unexpected token'); + } -var _esrecurse = require('esrecurse'); + // FieldType := + // FieldName + // | FieldName ':' TypeExpression + // + // FieldName := + // NameExpression + // | StringLiteral + // | NumberLiteral + // | ReservedIdentifier + function parseFieldType() { + var key; -var _esrecurse2 = _interopRequireDefault(_esrecurse); + key = parseFieldName(); + if (token === Token.COLON) { + consume(Token.COLON); + return { + type: Syntax.FieldType, + key: key, + value: parseTypeExpression() + }; + } + return { + type: Syntax.FieldType, + key: key, + value: null + }; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // RecordType := '{' FieldTypeList '}' + // + // FieldTypeList := + // <> + // | FieldType + // | FieldType ',' FieldTypeList + function parseRecordType() { + var fields; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + consume(Token.LBRACE, 'RecordType should start with {'); + fields = []; + if (token === Token.COMMA) { + consume(Token.COMMA); + } else { + while (token !== Token.RBRACE) { + fields.push(parseFieldType()); + if (token !== Token.RBRACE) { + expect(Token.COMMA); + } + } + } + expect(Token.RBRACE); + return { + type: Syntax.RecordType, + fields: fields + }; + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + // NameExpression := + // Identifier + // | TagIdentifier ':' Identifier + // + // Tag identifier is one of "module", "external" or "event" + // Identifier is the same as Token.NAME, including any dots, something like + // namespace.module.MyClass + function parseNameExpression() { + var name = value; + expect(Token.NAME); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - Copyright (C) 2015 Yusuke Suzuki - - 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 BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ + if (token === Token.COLON && (name === 'module' || name === 'external' || name === 'event')) { + consume(Token.COLON); + name += ':' + value; + expect(Token.NAME); + } -function getLast(xs) { - return xs[xs.length - 1] || null; -} + return { + type: Syntax.NameExpression, + name: name + }; + } -var PatternVisitor = function (_esrecurse$Visitor) { - _inherits(PatternVisitor, _esrecurse$Visitor); + // TypeExpressionList := + // TopLevelTypeExpression + // | TopLevelTypeExpression ',' TypeExpressionList + function parseTypeExpressionList() { + var elements = []; - _createClass(PatternVisitor, null, [{ - key: 'isPattern', - value: function isPattern(node) { - var nodeType = node.type; - return nodeType === _estraverse.Syntax.Identifier || nodeType === _estraverse.Syntax.ObjectPattern || nodeType === _estraverse.Syntax.ArrayPattern || nodeType === _estraverse.Syntax.SpreadElement || nodeType === _estraverse.Syntax.RestElement || nodeType === _estraverse.Syntax.AssignmentPattern; + elements.push(parseTop()); + while (token === Token.COMMA) { + consume(Token.COMMA); + elements.push(parseTop()); } - }]); - - function PatternVisitor(options, rootPattern, callback) { - _classCallCheck(this, PatternVisitor); + return elements; + } - var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(PatternVisitor).call(this, null, options)); + // TypeName := + // NameExpression + // | NameExpression TypeApplication + // + // TypeApplication := + // '.<' TypeExpressionList '>' + // | '<' TypeExpressionList '>' // this is extension of doctrine + function parseTypeName() { + var expr, applications; - _this.rootPattern = rootPattern; - _this.callback = callback; - _this.assignments = []; - _this.rightHandNodes = []; - _this.restElements = []; - return _this; + expr = parseNameExpression(); + if (token === Token.DOT_LT || token === Token.LT) { + next(); + applications = parseTypeExpressionList(); + expect(Token.GT); + return { + type: Syntax.TypeApplication, + expression: expr, + applications: applications + }; + } + return expr; } - _createClass(PatternVisitor, [{ - key: 'Identifier', - value: function Identifier(pattern) { - var lastRestElement = getLast(this.restElements); - this.callback(pattern, { - topLevel: pattern === this.rootPattern, - rest: lastRestElement != null && lastRestElement.argument === pattern, - assignments: this.assignments - }); - } - }, { - key: 'Property', - value: function Property(property) { - // Computed property's key is a right hand node. - if (property.computed) { - this.rightHandNodes.push(property.key); + // ResultType := + // <> + // | ':' void + // | ':' TypeExpression + // + // BNF is above + // but, we remove <> pattern, so token is always TypeToken::COLON + function parseResultType() { + consume(Token.COLON, 'ResultType should start with :'); + if (token === Token.NAME && value === 'void') { + consume(Token.NAME); + return { + type: Syntax.VoidLiteral + }; + } + return parseTypeExpression(); + } + + // ParametersType := + // RestParameterType + // | NonRestParametersType + // | NonRestParametersType ',' RestParameterType + // + // RestParameterType := + // '...' + // '...' Identifier + // + // NonRestParametersType := + // ParameterType ',' NonRestParametersType + // | ParameterType + // | OptionalParametersType + // + // OptionalParametersType := + // OptionalParameterType + // | OptionalParameterType, OptionalParametersType + // + // OptionalParameterType := ParameterType= + // + // ParameterType := TypeExpression | Identifier ':' TypeExpression + // + // Identifier is "new" or "this" + function parseParametersType() { + var params = [], + optionalSequence = false, + expr, + rest = false; + + while (token !== Token.RPAREN) { + if (token === Token.REST) { + // RestParameterType + consume(Token.REST); + rest = true; } - // If it's shorthand, its key is same as its value. - // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). - // If it's not shorthand, the name of new variable is its value's. - this.visit(property.value); - } - }, { - key: 'ArrayPattern', - value: function ArrayPattern(pattern) { - var i, iz, element; - for (i = 0, iz = pattern.elements.length; i < iz; ++i) { - element = pattern.elements[i]; - this.visit(element); + expr = parseTypeExpression(); + if (expr.type === Syntax.NameExpression && token === Token.COLON) { + // Identifier ':' TypeExpression + consume(Token.COLON); + expr = { + type: Syntax.ParameterType, + name: expr.name, + expression: parseTypeExpression() + }; } - } - }, { - key: 'AssignmentPattern', - value: function AssignmentPattern(pattern) { - this.assignments.push(pattern); - this.visit(pattern.left); - this.rightHandNodes.push(pattern.right); - this.assignments.pop(); - } - }, { - key: 'RestElement', - value: function RestElement(pattern) { - this.restElements.push(pattern); - this.visit(pattern.argument); - this.restElements.pop(); - } - }, { - key: 'MemberExpression', - value: function MemberExpression(node) { - // Computed property's key is a right hand node. - if (node.computed) { - this.rightHandNodes.push(node.property); + if (token === Token.EQUAL) { + consume(Token.EQUAL); + expr = { + type: Syntax.OptionalType, + expression: expr + }; + optionalSequence = true; + } else { + if (optionalSequence) { + utility.throwError('unexpected token'); + } + } + if (rest) { + expr = { + type: Syntax.RestType, + expression: expr + }; + } + params.push(expr); + if (token !== Token.RPAREN) { + expect(Token.COMMA); } - // the object is only read, write to its property. - this.rightHandNodes.push(node.object); } + return params; + } - // - // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. - // By spec, LeftHandSideExpression is Pattern or MemberExpression. - // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) - // But espree 2.0 and esprima 2.0 parse to ArrayExpression, ObjectExpression, etc... - // + // FunctionType := 'function' FunctionSignatureType + // + // FunctionSignatureType := + // | TypeParameters '(' ')' ResultType + // | TypeParameters '(' ParametersType ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType + function parseFunctionType() { + var isNew, thisBinding, params, result, fnType; + utility.assert(token === Token.NAME && value === 'function', 'FunctionType should start with \'function\''); + consume(Token.NAME); - }, { - key: 'SpreadElement', - value: function SpreadElement(node) { - this.visit(node.argument); - } - }, { - key: 'ArrayExpression', - value: function ArrayExpression(node) { - node.elements.forEach(this.visit, this); - } - }, { - key: 'AssignmentExpression', - value: function AssignmentExpression(node) { - this.assignments.push(node); - this.visit(node.left); - this.rightHandNodes.push(node.right); - this.assignments.pop(); - } - }, { - key: 'CallExpression', - value: function CallExpression(node) { - var _this2 = this; + // Google Closure Compiler is not implementing TypeParameters. + // So we do not. if we don't get '(', we see it as error. + expect(Token.LPAREN); - // arguments are right hand nodes. - node.arguments.forEach(function (a) { - _this2.rightHandNodes.push(a); - }); - this.visit(node.callee); + isNew = false; + params = []; + thisBinding = null; + if (token !== Token.RPAREN) { + // ParametersType or 'this' + if (token === Token.NAME && (value === 'this' || value === 'new')) { + // 'this' or 'new' + // 'new' is Closure Compiler extension + isNew = value === 'new'; + consume(Token.NAME); + expect(Token.COLON); + thisBinding = parseTypeName(); + if (token === Token.COMMA) { + consume(Token.COMMA); + params = parseParametersType(); + } + } else { + params = parseParametersType(); + } } - }]); - return PatternVisitor; -}(_esrecurse2.default.Visitor); + expect(Token.RPAREN); -/* vim: set sw=4 ts=4 et tw=80 : */ + result = null; + if (token === Token.COLON) { + result = parseResultType(); + } + fnType = { + type: Syntax.FunctionType, + params: params, + result: result + }; + if (thisBinding) { + // avoid adding null 'new' and 'this' properties + fnType['this'] = thisBinding; + if (isNew) { + fnType['new'] = true; + } + } + return fnType; + } -exports.default = PatternVisitor; + // BasicTypeExpression := + // '*' + // | 'null' + // | 'undefined' + // | TypeName + // | FunctionType + // | UnionType + // | RecordType + // | ArrayType + function parseBasicTypeExpression() { + var context; + switch (token) { + case Token.STAR: + consume(Token.STAR); + return { + type: Syntax.AllLiteral + }; + case Token.LPAREN: + return parseUnionType(); -},{"esrecurse":90,"estraverse":92}],82:[function(require,module,exports){ -"use strict"; + case Token.LBRACK: + return parseArrayType(); -Object.defineProperty(exports, "__esModule", { - value: true -}); + case Token.LBRACE: + return parseRecordType(); -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + case Token.NAME: + if (value === 'null') { + consume(Token.NAME); + return { + type: Syntax.NullLiteral + }; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + if (value === 'undefined') { + consume(Token.NAME); + return { + type: Syntax.UndefinedLiteral + }; + } -/* - Copyright (C) 2015 Yusuke Suzuki + if (value === 'true' || value === 'false') { + consume(Token.NAME); + return { + type: Syntax.BooleanLiteralType, + value: value === 'true' + }; + } - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + context = Context.save(); + if (value === 'function') { + try { + return parseFunctionType(); + } catch (e) { + context.restore(); + } + } - * 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. + return parseTypeName(); - 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 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. -*/ + case Token.STRING: + next(); + return { + type: Syntax.StringLiteralType, + value: value + }; -var READ = 0x1; -var WRITE = 0x2; -var RW = READ | WRITE; + case Token.NUMBER: + next(); + return { + type: Syntax.NumericLiteralType, + value: value + }; -/** - * A Reference represents a single occurrence of an identifier in code. - * @class Reference - */ + default: + utility.throwError('unexpected token'); + } + } -var Reference = function () { - function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { - _classCallCheck(this, Reference); + // TypeExpression := + // BasicTypeExpression + // | '?' BasicTypeExpression + // | '!' BasicTypeExpression + // | BasicTypeExpression '?' + // | BasicTypeExpression '!' + // | '?' + // | BasicTypeExpression '[]' + function parseTypeExpression() { + var expr; - /** - * Identifier syntax node. - * @member {esprima#Identifier} Reference#identifier - */ - this.identifier = ident; - /** - * Reference to the enclosing Scope. - * @member {Scope} Reference#from - */ - this.from = scope; - /** - * Whether the reference comes from a dynamic scope (such as 'eval', - * 'with', etc.), and may be trapped by dynamic scopes. - * @member {boolean} Reference#tainted - */ - this.tainted = false; - /** - * The variable this reference is resolved with. - * @member {Variable} Reference#resolved - */ - this.resolved = null; - /** - * The read-write mode of the reference. (Value is one of {@link - * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). - * @member {number} Reference#flag - * @private - */ - this.flag = flag; - if (this.isWrite()) { - /** - * If reference is writeable, this is the tree being written to it. - * @member {esprima#Node} Reference#writeExpr - */ - this.writeExpr = writeExpr; - /** - * Whether the Reference might refer to a partial value of writeExpr. - * @member {boolean} Reference#partial - */ - this.partial = partial; - /** - * Whether the Reference is to write of initialization. - * @member {boolean} Reference#init - */ - this.init = init; - } - this.__maybeImplicitGlobal = maybeImplicitGlobal; - } + if (token === Token.QUESTION) { + consume(Token.QUESTION); + if (token === Token.COMMA || token === Token.EQUAL || token === Token.RBRACE || token === Token.RPAREN || token === Token.PIPE || token === Token.EOF || token === Token.RBRACK || token === Token.GT) { + return { + type: Syntax.NullableLiteral + }; + } + return { + type: Syntax.NullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } - /** - * Whether the reference is static. - * @method Reference#isStatic - * @return {boolean} - */ + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } + expr = parseBasicTypeExpression(); + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: expr, + prefix: false + }; + } - _createClass(Reference, [{ - key: "isStatic", - value: function isStatic() { - return !this.tainted && this.resolved && this.resolved.scope.isStatic(); - } + if (token === Token.QUESTION) { + consume(Token.QUESTION); + return { + type: Syntax.NullableType, + expression: expr, + prefix: false + }; + } - /** - * Whether the reference is writeable. - * @method Reference#isWrite - * @return {boolean} - */ + if (token === Token.LBRACK) { + consume(Token.LBRACK); + expect(Token.RBRACK, 'expected an array-style type declaration (' + value + '[])'); + return { + type: Syntax.TypeApplication, + expression: { + type: Syntax.NameExpression, + name: 'Array' + }, + applications: [expr] + }; + } - }, { - key: "isWrite", - value: function isWrite() { - return !!(this.flag & Reference.WRITE); + return expr; } - /** - * Whether the reference is readable. - * @method Reference#isRead - * @return {boolean} - */ + // TopLevelTypeExpression := + // TypeExpression + // | TypeUnionList + // + // This rule is Google Closure Compiler extension, not ES4 + // like, + // { number | string } + // If strict to ES4, we should write it as + // { (number|string) } + function parseTop() { + var expr, elements; - }, { - key: "isRead", - value: function isRead() { - return !!(this.flag & Reference.READ); - } + expr = parseTypeExpression(); + if (token !== Token.PIPE) { + return expr; + } - /** - * Whether the reference is read-only. - * @method Reference#isReadOnly - * @return {boolean} - */ + elements = [expr]; + consume(Token.PIPE); + while (true) { + elements.push(parseTypeExpression()); + if (token !== Token.PIPE) { + break; + } + consume(Token.PIPE); + } - }, { - key: "isReadOnly", - value: function isReadOnly() { - return this.flag === Reference.READ; + return { + type: Syntax.UnionType, + elements: elements + }; } - /** - * Whether the reference is write-only. - * @method Reference#isWriteOnly - * @return {boolean} - */ + function parseTopParamType() { + var expr; - }, { - key: "isWriteOnly", - value: function isWriteOnly() { - return this.flag === Reference.WRITE; - } + if (token === Token.REST) { + consume(Token.REST); + return { + type: Syntax.RestType, + expression: parseTop() + }; + } - /** - * Whether the reference is read-write. - * @method Reference#isReadWrite - * @return {boolean} - */ + expr = parseTop(); + if (token === Token.EQUAL) { + consume(Token.EQUAL); + return { + type: Syntax.OptionalType, + expression: expr + }; + } - }, { - key: "isReadWrite", - value: function isReadWrite() { - return this.flag === Reference.RW; + return expr; } - }]); - return Reference; -}(); + function parseType(src, opt) { + var expr; -/** - * @constant Reference.READ - * @private - */ + source = src; + length = source.length; + index = 0; + previous = 0; + next(); + expr = parseTop(); -exports.default = Reference; -Reference.READ = READ; -/** - * @constant Reference.WRITE - * @private - */ -Reference.WRITE = WRITE; -/** - * @constant Reference.RW - * @private - */ -Reference.RW = RW; + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } -/* vim: set sw=4 ts=4 et tw=80 : */ + if (token !== Token.EOF) { + utility.throwError('not reach to EOF'); + } + return expr; + } -},{}],83:[function(require,module,exports){ -'use strict'; + function parseParamType(src, opt) { + var expr; -Object.defineProperty(exports, "__esModule", { - value: true -}); + source = src; + length = source.length; + index = 0; + previous = 0; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + next(); + expr = parseTopParamType(); -var _estraverse = require('estraverse'); - -var _esrecurse = require('esrecurse'); + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } -var _esrecurse2 = _interopRequireDefault(_esrecurse); + if (token !== Token.EOF) { + utility.throwError('not reach to EOF'); + } -var _reference = require('./reference'); + return expr; + } -var _reference2 = _interopRequireDefault(_reference); + function stringifyImpl(node, compact, topLevel) { + var result, i, iz; -var _variable = require('./variable'); + switch (node.type) { + case Syntax.NullableLiteral: + result = '?'; + break; -var _variable2 = _interopRequireDefault(_variable); + case Syntax.AllLiteral: + result = '*'; + break; -var _patternVisitor = require('./pattern-visitor'); + case Syntax.NullLiteral: + result = 'null'; + break; -var _patternVisitor2 = _interopRequireDefault(_patternVisitor); + case Syntax.UndefinedLiteral: + result = 'undefined'; + break; -var _definition = require('./definition'); + case Syntax.VoidLiteral: + result = 'void'; + break; -var _assert = require('assert'); + case Syntax.UnionType: + if (!topLevel) { + result = '('; + } else { + result = ''; + } -var _assert2 = _interopRequireDefault(_assert); + for (i = 0, iz = node.elements.length; i < iz; ++i) { + result += stringifyImpl(node.elements[i], compact); + if (i + 1 !== iz) { + result += '|'; + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!topLevel) { + result += ')'; + } + break; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + case Syntax.ArrayType: + result = '['; + for (i = 0, iz = node.elements.length; i < iz; ++i) { + result += stringifyImpl(node.elements[i], compact); + if (i + 1 !== iz) { + result += compact ? ',' : ', '; + } + } + result += ']'; + break; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + case Syntax.RecordType: + result = '{'; + for (i = 0, iz = node.fields.length; i < iz; ++i) { + result += stringifyImpl(node.fields[i], compact); + if (i + 1 !== iz) { + result += compact ? ',' : ', '; + } + } + result += '}'; + break; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* - Copyright (C) 2015 Yusuke Suzuki - - 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 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. - */ + case Syntax.FieldType: + if (node.value) { + result = node.key + (compact ? ':' : ': ') + stringifyImpl(node.value, compact); + } else { + result = node.key; + } + break; + case Syntax.FunctionType: + result = compact ? 'function(' : 'function ('; -function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { - // Call the callback at left hand identifier nodes, and Collect right hand nodes. - var visitor = new _patternVisitor2.default(options, rootPattern, callback); - visitor.visit(rootPattern); + if (node['this']) { + if (node['new']) { + result += compact ? 'new:' : 'new: '; + } else { + result += compact ? 'this:' : 'this: '; + } - // Process the right hand nodes recursively. - if (referencer != null) { - visitor.rightHandNodes.forEach(referencer.visit, referencer); - } -} + result += stringifyImpl(node['this'], compact); -// Importing ImportDeclaration. -// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation -// https://github.com/estree/estree/blob/master/es6.md#importdeclaration -// FIXME: Now, we don't create module environment, because the context is -// implementation dependent. + if (node.params.length !== 0) { + result += compact ? ',' : ', '; + } + } -var Importer = function (_esrecurse$Visitor) { - _inherits(Importer, _esrecurse$Visitor); + for (i = 0, iz = node.params.length; i < iz; ++i) { + result += stringifyImpl(node.params[i], compact); + if (i + 1 !== iz) { + result += compact ? ',' : ', '; + } + } - function Importer(declaration, referencer) { - _classCallCheck(this, Importer); + result += ')'; - var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Importer).call(this, null, referencer.options)); + if (node.result) { + result += (compact ? ':' : ': ') + stringifyImpl(node.result, compact); + } + break; - _this.declaration = declaration; - _this.referencer = referencer; - return _this; - } + case Syntax.ParameterType: + result = node.name + (compact ? ':' : ': ') + stringifyImpl(node.expression, compact); + break; - _createClass(Importer, [{ - key: 'visitImport', - value: function visitImport(id, specifier) { - var _this2 = this; + case Syntax.RestType: + result = '...'; + if (node.expression) { + result += stringifyImpl(node.expression, compact); + } + break; - this.referencer.visitPattern(id, function (pattern) { - _this2.referencer.currentScope().__define(pattern, new _definition.Definition(_variable2.default.ImportBinding, pattern, specifier, _this2.declaration, null, null)); - }); - } - }, { - key: 'ImportNamespaceSpecifier', - value: function ImportNamespaceSpecifier(node) { - var local = node.local || node.id; - if (local) { - this.visitImport(local, node); - } - } - }, { - key: 'ImportDefaultSpecifier', - value: function ImportDefaultSpecifier(node) { - var local = node.local || node.id; - this.visitImport(local, node); - } - }, { - key: 'ImportSpecifier', - value: function ImportSpecifier(node) { - var local = node.local || node.id; - if (node.name) { - this.visitImport(node.name, node); - } else { - this.visitImport(local, node); - } - } - }]); + case Syntax.NonNullableType: + if (node.prefix) { + result = '!' + stringifyImpl(node.expression, compact); + } else { + result = stringifyImpl(node.expression, compact) + '!'; + } + break; - return Importer; -}(_esrecurse2.default.Visitor); + case Syntax.OptionalType: + result = stringifyImpl(node.expression, compact) + '='; + break; -// Referencing variables and creating bindings. + case Syntax.NullableType: + if (node.prefix) { + result = '?' + stringifyImpl(node.expression, compact); + } else { + result = stringifyImpl(node.expression, compact) + '?'; + } + break; + case Syntax.NameExpression: + result = node.name; + break; -var Referencer = function (_esrecurse$Visitor2) { - _inherits(Referencer, _esrecurse$Visitor2); + case Syntax.TypeApplication: + result = stringifyImpl(node.expression, compact) + '.<'; + for (i = 0, iz = node.applications.length; i < iz; ++i) { + result += stringifyImpl(node.applications[i], compact); + if (i + 1 !== iz) { + result += compact ? ',' : ', '; + } + } + result += '>'; + break; - function Referencer(options, scopeManager) { - _classCallCheck(this, Referencer); + case Syntax.StringLiteralType: + result = '"' + node.value + '"'; + break; - var _this3 = _possibleConstructorReturn(this, Object.getPrototypeOf(Referencer).call(this, null, options)); + case Syntax.NumericLiteralType: + result = String(node.value); + break; - _this3.options = options; - _this3.scopeManager = scopeManager; - _this3.parent = null; - _this3.isInnerMethodDefinition = false; - return _this3; - } + case Syntax.BooleanLiteralType: + result = String(node.value); + break; - _createClass(Referencer, [{ - key: 'currentScope', - value: function currentScope() { - return this.scopeManager.__currentScope; - } - }, { - key: 'close', - value: function close(node) { - while (this.currentScope() && node === this.currentScope().block) { - this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); - } - } - }, { - key: 'pushInnerMethodDefinition', - value: function pushInnerMethodDefinition(isInnerMethodDefinition) { - var previous = this.isInnerMethodDefinition; - this.isInnerMethodDefinition = isInnerMethodDefinition; - return previous; - } - }, { - key: 'popInnerMethodDefinition', - value: function popInnerMethodDefinition(isInnerMethodDefinition) { - this.isInnerMethodDefinition = isInnerMethodDefinition; - } - }, { - key: 'materializeTDZScope', - value: function materializeTDZScope(node, iterationNode) { - // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation - // TDZ scope hides the declaration's names. - this.scopeManager.__nestTDZScope(node, iterationNode); - this.visitVariableDeclaration(this.currentScope(), _variable2.default.TDZ, iterationNode.left, 0, true); + default: + utility.throwError('Unknown type ' + node.type); } - }, { - key: 'materializeIterationScope', - value: function materializeIterationScope(node) { - var _this4 = this; - // Generate iteration scope for upper ForIn/ForOf Statements. - var letOrConstDecl; - this.scopeManager.__nestForScope(node); - letOrConstDecl = node.left; - this.visitVariableDeclaration(this.currentScope(), _variable2.default.Variable, letOrConstDecl, 0); - this.visitPattern(letOrConstDecl.declarations[0].id, function (pattern) { - _this4.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, null, true, true); - }); - } - }, { - key: 'referencingDefaultValue', - value: function referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { - var scope = this.currentScope(); - assignments.forEach(function (assignment) { - scope.__referencing(pattern, _reference2.default.WRITE, assignment.right, maybeImplicitGlobal, pattern !== assignment.left, init); - }); - } - }, { - key: 'visitPattern', - value: function visitPattern(node, options, callback) { - if (typeof options === 'function') { - callback = options; - options = { processRightHandNodes: false }; - } - traverseIdentifierInPattern(this.options, node, options.processRightHandNodes ? this : null, callback); + return result; + } + + function stringify(node, options) { + if (options == null) { + options = {}; } - }, { - key: 'visitFunction', - value: function visitFunction(node) { - var _this5 = this; + return stringifyImpl(node, options.compact, options.topLevel); + } - var i, iz; - // FunctionDeclaration name is defined in upper scope - // NOTE: Not referring variableScope. It is intended. - // Since - // in ES5, FunctionDeclaration should be in FunctionBody. - // in ES6, FunctionDeclaration should be block scoped. - if (node.type === _estraverse.Syntax.FunctionDeclaration) { - // id is defined in upper scope - this.currentScope().__define(node.id, new _definition.Definition(_variable2.default.FunctionName, node.id, node, null, null, null)); - } + exports.parseType = parseType; + exports.parseParamType = parseParamType; + exports.stringify = stringify; + exports.Syntax = Syntax; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ - // FunctionExpression with name creates its special scope; - // FunctionExpressionNameScope. - if (node.type === _estraverse.Syntax.FunctionExpression && node.id) { - this.scopeManager.__nestFunctionExpressionNameScope(node); - } +},{"./utility":56,"esutils":76}],56:[function(require,module,exports){ +'use strict'; - // Consider this function is in the MethodDefinition. - this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); +/* + * @fileoverview Utilities for Doctrine + * @author Yusuke Suzuki + */ - // Process parameter declarations. - for (i = 0, iz = node.params.length; i < iz; ++i) { - this.visitPattern(node.params[i], { processRightHandNodes: true }, function (pattern, info) { - _this5.currentScope().__define(pattern, new _definition.ParameterDefinition(pattern, node, i, info.rest)); +(function () { + 'use strict'; - _this5.referencingDefaultValue(pattern, info.assignments, null, true); - }); - } + var VERSION; - // if there's a rest argument, add that - if (node.rest) { - this.visitPattern({ - type: 'RestElement', - argument: node.rest - }, function (pattern) { - _this5.currentScope().__define(pattern, new _definition.ParameterDefinition(pattern, node, node.params.length, true)); - }); - } + VERSION = require('../package.json').version; + exports.VERSION = VERSION; - // Skip BlockStatement to prevent creating BlockStatement scope. - if (node.body.type === _estraverse.Syntax.BlockStatement) { - this.visitChildren(node.body); - } else { - this.visit(node.body); - } + function DoctrineError(message) { + this.name = 'DoctrineError'; + this.message = message; + } + DoctrineError.prototype = function () { + var Middle = function Middle() {}; + Middle.prototype = Error.prototype; + return new Middle(); + }(); + DoctrineError.prototype.constructor = DoctrineError; + exports.DoctrineError = DoctrineError; - this.close(node); - } - }, { - key: 'visitClass', - value: function visitClass(node) { - if (node.type === _estraverse.Syntax.ClassDeclaration) { - this.currentScope().__define(node.id, new _definition.Definition(_variable2.default.ClassName, node.id, node, null, null, null)); - } + function throwError(message) { + throw new DoctrineError(message); + } + exports.throwError = throwError; - // FIXME: Maybe consider TDZ. - this.visit(node.superClass); + exports.assert = require('assert'); +})(); - this.scopeManager.__nestClassScope(node); +/* vim: set sw=4 ts=4 et tw=80 : */ - if (node.id) { - this.currentScope().__define(node.id, new _definition.Definition(_variable2.default.ClassName, node.id, node)); - } - this.visit(node.body); +},{"../package.json":57,"assert":47}],57:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + { + "raw": "doctrine@^2.0.0", + "scope": null, + "escapedName": "doctrine", + "name": "doctrine", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "D:\\users\\r2g\\exps\\eslint-4.5.0" + ] + ], + "_from": "doctrine@>=2.0.0 <3.0.0", + "_id": "doctrine@2.0.0", + "_inCache": true, + "_location": "/doctrine", + "_nodeVersion": "4.4.2", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/doctrine-2.0.0.tgz_1479232728285_0.34204454137943685" + }, + "_npmUser": { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + }, + "_npmVersion": "2.15.0", + "_phantomChildren": {}, + "_requested": { + "raw": "doctrine@^2.0.0", + "scope": null, + "escapedName": "doctrine", + "name": "doctrine", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.0.0.tgz", + "_shasum": "c73d8d2909d22291e1a007a395804da8b665fe63", + "_shrinkwrap": null, + "_spec": "doctrine@^2.0.0", + "_where": "D:\\users\\r2g\\exps\\eslint-4.5.0", + "bugs": { + "url": "https://github.com/eslint/doctrine/issues" + }, + "dependencies": { + "esutils": "^2.0.2", + "isarray": "^1.0.0" + }, + "description": "JSDoc parser", + "devDependencies": { + "coveralls": "^2.11.2", + "dateformat": "^1.0.11", + "eslint": "^1.10.3", + "eslint-release": "^0.10.0", + "istanbul": "^0.4.1", + "linefix": "^0.1.1", + "mocha": "^2.3.3", + "npm-license": "^0.3.1", + "semver": "^5.0.3", + "shelljs": "^0.5.3", + "shelljs-nodecli": "^0.1.1", + "should": "^5.0.1" + }, + "directories": { + "lib": "./lib" + }, + "dist": { + "shasum": "c73d8d2909d22291e1a007a395804da8b665fe63", + "tarball": "https://registry.npmjs.org/doctrine/-/doctrine-2.0.0.tgz" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "lib", + "LICENSE.BSD", + "LICENSE.closure-compiler", + "LICENSE.esprima", + "README.md" + ], + "gitHead": "46c600f27f54b3ab6b0b8a9ac9f97c807ffa95ef", + "homepage": "https://github.com/eslint/doctrine", + "license": "Apache-2.0", + "main": "lib/doctrine.js", + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + { + "name": "eslint", + "email": "nicholas+eslint@nczconsulting.com" + }, + { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + } + ], + "name": "doctrine", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/doctrine.git" + }, + "scripts": { + "alpharelease": "eslint-prerelease alpha", + "betarelease": "eslint-prerelease beta", + "ci-release": "eslint-ci-release", + "lint": "eslint lib/", + "release": "eslint-release", + "test": "npm run lint && node Makefile.js test" + }, + "version": "2.0.0" +} - this.close(node); - } - }, { - key: 'visitProperty', - value: function visitProperty(node) { - var previous, isMethodDefinition; - if (node.computed) { - this.visit(node.key); - } +},{}],58:[function(require,module,exports){ +/* + Copyright (C) 2015 Yusuke Suzuki - isMethodDefinition = node.type === _estraverse.Syntax.MethodDefinition; - if (isMethodDefinition) { - previous = this.pushInnerMethodDefinition(true); - } - this.visit(node.value); - if (isMethodDefinition) { - this.popInnerMethodDefinition(previous); - } - } - }, { - key: 'visitForIn', - value: function visitForIn(node) { - var _this6 = this; + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - if (node.left.type === _estraverse.Syntax.VariableDeclaration && node.left.kind !== 'var') { - this.materializeTDZScope(node.right, node); - this.visit(node.right); - this.close(node.right); + * 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.materializeIterationScope(node); - this.visit(node.body); - this.close(node); - } else { - if (node.left.type === _estraverse.Syntax.VariableDeclaration) { - this.visit(node.left); - this.visitPattern(node.left.declarations[0].id, function (pattern) { - _this6.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, null, true, true); - }); - } else { - this.visitPattern(node.left, { processRightHandNodes: true }, function (pattern, info) { - var maybeImplicitGlobal = null; - if (!_this6.currentScope().isStrict) { - maybeImplicitGlobal = { - pattern: pattern, - node: node - }; - } - _this6.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); - _this6.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, maybeImplicitGlobal, true, false); - }); - } - this.visit(node.right); - this.visit(node.body); - } - } - }, { - key: 'visitVariableDeclaration', - value: function visitVariableDeclaration(variableTargetScope, type, node, index, fromTDZ) { - var _this7 = this; + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +"use strict"; - // If this was called to initialize a TDZ scope, this needs to make definitions, but doesn't make references. - var decl, init; +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - decl = node.declarations[index]; - init = decl.init; - this.visitPattern(decl.id, { processRightHandNodes: !fromTDZ }, function (pattern, info) { - variableTargetScope.__define(pattern, new _definition.Definition(type, pattern, decl, node, index, node.kind)); +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - if (!fromTDZ) { - _this7.referencingDefaultValue(pattern, info.assignments, null, true); - } - if (init) { - _this7.currentScope().__referencing(pattern, _reference2.default.WRITE, init, null, !info.topLevel, true); - } - }); - } - }, { - key: 'AssignmentExpression', - value: function AssignmentExpression(node) { - var _this8 = this; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - if (_patternVisitor2.default.isPattern(node.left)) { - if (node.operator === '=') { - this.visitPattern(node.left, { processRightHandNodes: true }, function (pattern, info) { - var maybeImplicitGlobal = null; - if (!_this8.currentScope().isStrict) { - maybeImplicitGlobal = { - pattern: pattern, - node: node - }; - } - _this8.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); - _this8.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); - }); - } else { - this.currentScope().__referencing(node.left, _reference2.default.RW, node.right); - } - } else { - this.visit(node.left); - } - this.visit(node.right); - } - }, { - key: 'CatchClause', - value: function CatchClause(node) { - var _this9 = this; +var Variable = require("./variable"); - this.scopeManager.__nestCatchScope(node); +/** + * @class Definition + */ - this.visitPattern(node.param, { processRightHandNodes: true }, function (pattern, info) { - _this9.currentScope().__define(pattern, new _definition.Definition(_variable2.default.CatchClause, node.param, node, null, null, null)); - _this9.referencingDefaultValue(pattern, info.assignments, null, true); - }); - this.visit(node.body); +var Definition = function Definition(type, name, node, parent, index, kind) { + _classCallCheck(this, Definition); - this.close(node); - } - }, { - key: 'Program', - value: function Program(node) { - this.scopeManager.__nestGlobalScope(node); + /** + * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; - if (this.scopeManager.__isNodejsScope()) { - // Force strictness of GlobalScope to false when using node.js scope. - this.currentScope().isStrict = false; - this.scopeManager.__nestFunctionScope(node, false); - } + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; - if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { - this.scopeManager.__nestModuleScope(node); - } + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; - if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { - this.currentScope().isStrict = true; - } + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; - this.visitChildren(node); - this.close(node); - } - }, { - key: 'Identifier', - value: function Identifier(node) { - this.currentScope().__referencing(node); - } - }, { - key: 'UpdateExpression', - value: function UpdateExpression(node) { - if (_patternVisitor2.default.isPattern(node.argument)) { - this.currentScope().__referencing(node.argument, _reference2.default.RW, null); - } else { - this.visitChildren(node); - } - } - }, { - key: 'MemberExpression', - value: function MemberExpression(node) { - this.visit(node.object); - if (node.computed) { - this.visit(node.property); - } - } - }, { - key: 'Property', - value: function Property(node) { - this.visitProperty(node); - } - }, { - key: 'MethodDefinition', - value: function MethodDefinition(node) { - this.visitProperty(node); - } - }, { - key: 'BreakStatement', - value: function BreakStatement() {} - }, { - key: 'ContinueStatement', - value: function ContinueStatement() {} - }, { - key: 'LabeledStatement', - value: function LabeledStatement(node) { - this.visit(node.body); - } - }, { - key: 'ForStatement', - value: function ForStatement(node) { - // Create ForStatement declaration. - // NOTE: In ES6, ForStatement dynamically generates - // per iteration environment. However, escope is - // a static analyzer, we only generate one scope for ForStatement. - if (node.init && node.init.type === _estraverse.Syntax.VariableDeclaration && node.init.kind !== 'var') { - this.scopeManager.__nestForScope(node); - } + /** + * @member {Number?} Definition#index - the index in the declaration statement. + */ + this.index = index; - this.visitChildren(node); + /** + * @member {String?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; +}; - this.close(node); - } - }, { - key: 'ClassExpression', - value: function ClassExpression(node) { - this.visitClass(node); - } - }, { - key: 'ClassDeclaration', - value: function ClassDeclaration(node) { - this.visitClass(node); - } - }, { - key: 'CallExpression', - value: function CallExpression(node) { - // Check this is direct call to eval - if (!this.scopeManager.__ignoreEval() && node.callee.type === _estraverse.Syntax.Identifier && node.callee.name === 'eval') { - // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and - // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. - this.currentScope().variableScope.__detectEval(); - } - this.visitChildren(node); - } - }, { - key: 'BlockStatement', - value: function BlockStatement(node) { - if (this.scopeManager.__isES6()) { - this.scopeManager.__nestBlockScope(node); - } +/** + * @class ParameterDefinition + */ - this.visitChildren(node); - this.close(node); - } - }, { - key: 'ThisExpression', - value: function ThisExpression() { - this.currentScope().variableScope.__detectThis(); - } - }, { - key: 'WithStatement', - value: function WithStatement(node) { - this.visit(node.object); - // Then nest scope for WithStatement. - this.scopeManager.__nestWithScope(node); +var ParameterDefinition = function (_Definition) { + _inherits(ParameterDefinition, _Definition); - this.visit(node.body); + function ParameterDefinition(name, node, index, rest) { + _classCallCheck(this, ParameterDefinition); - this.close(node); - } - }, { - key: 'VariableDeclaration', - value: function VariableDeclaration(node) { - var variableTargetScope, i, iz, decl; - variableTargetScope = node.kind === 'var' ? this.currentScope().variableScope : this.currentScope(); - for (i = 0, iz = node.declarations.length; i < iz; ++i) { - decl = node.declarations[i]; - this.visitVariableDeclaration(variableTargetScope, _variable2.default.Variable, node, i); - if (decl.init) { - this.visit(decl.init); - } - } - } + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + var _this = _possibleConstructorReturn(this, (ParameterDefinition.__proto__ || Object.getPrototypeOf(ParameterDefinition)).call(this, Variable.Parameter, name, node, null, index, null)); - // sec 13.11.8 + _this.rest = rest; + return _this; + } - }, { - key: 'SwitchStatement', - value: function SwitchStatement(node) { - var i, iz; + return ParameterDefinition; +}(Definition); - this.visit(node.discriminant); +module.exports = { + ParameterDefinition: ParameterDefinition, + Definition: Definition +}; - if (this.scopeManager.__isES6()) { - this.scopeManager.__nestSwitchScope(node); - } +/* vim: set sw=4 ts=4 et tw=80 : */ - for (i = 0, iz = node.cases.length; i < iz; ++i) { - this.visit(node.cases[i]); - } +},{"./variable":65}],59:[function(require,module,exports){ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda - this.close(node); - } - }, { - key: 'FunctionDeclaration', - value: function FunctionDeclaration(node) { - this.visitFunction(node); - } - }, { - key: 'FunctionExpression', - value: function FunctionExpression(node) { - this.visitFunction(node); - } - }, { - key: 'ForOfStatement', - value: function ForOfStatement(node) { - this.visitForIn(node); - } - }, { - key: 'ForInStatement', - value: function ForInStatement(node) { - this.visitForIn(node); - } - }, { - key: 'ArrowFunctionExpression', - value: function ArrowFunctionExpression(node) { - this.visitFunction(node); - } - }, { - key: 'ImportDeclaration', - value: function ImportDeclaration(node) { - var importer; + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - (0, _assert2.default)(this.scopeManager.__isES6() && this.scopeManager.isModule(), 'ImportDeclaration should appear when the mode is ES6 and in the module context.'); + * 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. - importer = new Importer(node, this); - importer.visit(node); - } - }, { - key: 'visitExportDeclaration', - value: function visitExportDeclaration(node) { - if (node.source) { - return; - } - if (node.declaration) { - this.visit(node.declaration); - return; - } + 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 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. +*/ - this.visitChildren(node); - } - }, { - key: 'ExportDeclaration', - value: function ExportDeclaration(node) { - this.visitExportDeclaration(node); - } - }, { - key: 'ExportNamedDeclaration', - value: function ExportNamedDeclaration(node) { - this.visitExportDeclaration(node); - } - }, { - key: 'ExportSpecifier', - value: function ExportSpecifier(node) { - var local = node.id || node.local; - this.visit(local); - } - }, { - key: 'MetaProperty', - value: function MetaProperty() { - // do nothing. - } - }]); +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. espree is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ +"use strict"; - return Referencer; -}(_esrecurse2.default.Visitor); +/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */ -/* vim: set sw=4 ts=4 et tw=80 : */ +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var assert = require("assert"); + +var ScopeManager = require("./scope-manager"); +var Referencer = require("./referencer"); +var Reference = require("./reference"); +var Variable = require("./variable"); +var Scope = require("./scope").Scope; +var version = require("../package.json").version; +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + directive: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration" + }; +} -exports.default = Referencer; +/** + * Preform deep update on option object + * @param {Object} target - Options + * @param {Object} override - Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { + /** + * Is hash object + * @param {Object} value - Test value + * @returns {boolean} Result + */ + function isHashObject(value) { + return (typeof value === "undefined" ? "undefined" : _typeof(value)) === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + } -},{"./definition":79,"./pattern-visitor":81,"./reference":82,"./variable":86,"assert":5,"esrecurse":90,"estraverse":92}],84:[function(require,module,exports){ -'use strict'; + for (var key in override) { + if (override.hasOwnProperty(key)) { + var val = override[key]; -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* - Copyright (C) 2015 Yusuke Suzuki - - 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 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. - */ +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {espree.Tree} tree - Abstract Syntax Tree + * @param {Object} providedOptions - Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag + * @param {boolean} [providedOptions.directive=false]- the directive flag + * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module' + * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered + * @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + var options = updateDeeply(defaultOptions(), providedOptions); + var scopeManager = new ScopeManager(options); + var referencer = new Referencer(options, scopeManager); -var _es6WeakMap = require('es6-weak-map'); + referencer.visit(tree); -var _es6WeakMap2 = _interopRequireDefault(_es6WeakMap); + assert(scopeManager.__currentScope === null, "currentScope should be null."); -var _scope = require('./scope'); + return scopeManager; +} -var _scope2 = _interopRequireDefault(_scope); +module.exports = { -var _assert = require('assert'); + /** @name module:escope.version */ + version: version, -var _assert2 = _interopRequireDefault(_assert); + /** @name module:escope.Reference */ + Reference: Reference, -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** @name module:escope.Variable */ + Variable: Variable, -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** @name module:escope.Scope */ + Scope: Scope, -/** - * @class ScopeManager - */ + /** @name module:escope.ScopeManager */ + ScopeManager: ScopeManager, + analyze: analyze +}; -var ScopeManager = function () { - function ScopeManager(options) { - _classCallCheck(this, ScopeManager); +/* vim: set sw=4 ts=4 et tw=80 : */ - this.scopes = []; - this.globalScope = null; - this.__nodeToScope = new _es6WeakMap2.default(); - this.__currentScope = null; - this.__options = options; - this.__declaredVariables = new _es6WeakMap2.default(); - } +},{"../package.json":66,"./reference":61,"./referencer":62,"./scope":64,"./scope-manager":63,"./variable":65,"assert":47}],60:[function(require,module,exports){ +/* + Copyright (C) 2015 Yusuke Suzuki - _createClass(ScopeManager, [{ - key: '__useDirective', - value: function __useDirective() { - return this.__options.directive; - } - }, { - key: '__isOptimistic', - value: function __isOptimistic() { - return this.__options.optimistic; - } - }, { - key: '__ignoreEval', - value: function __ignoreEval() { - return this.__options.ignoreEval; - } - }, { - key: '__isNodejsScope', - value: function __isNodejsScope() { - return this.__options.nodejsScope; - } - }, { - key: 'isModule', - value: function isModule() { - return this.__options.sourceType === 'module'; - } - }, { - key: 'isImpliedStrict', - value: function isImpliedStrict() { - return this.__options.impliedStrict; - } - }, { - key: 'isStrictModeSupported', - value: function isStrictModeSupported() { - return this.__options.ecmaVersion >= 5; - } + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - // Returns appropriate scope for this node. + * 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. - }, { - key: '__get', - value: function __get(node) { - return this.__nodeToScope.get(node); - } + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +"use strict"; - /** - * Get variables that are declared by the node. - * - * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. - * If the node declares nothing, this method returns an empty array. - * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. - * - * @param {Esprima.Node} node - a node to get. - * @returns {Variable[]} variables that declared by the node. - */ +/* eslint-disable no-undefined */ - }, { - key: 'getDeclaredVariables', - value: function getDeclaredVariables(node) { - return this.__declaredVariables.get(node) || []; - } +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - /** - * acquire scope from node. - * @method ScopeManager#acquire - * @param {Esprima.Node} node - node for the acquired scope. - * @param {boolean=} inner - look up the most inner scope, default value is false. - * @return {Scope?} - */ +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - }, { - key: 'acquire', - value: function acquire(node, inner) { - var scopes, scope, i, iz; +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - function predicate(scope) { - if (scope.type === 'function' && scope.functionExpressionScope) { - return false; - } - if (scope.type === 'TDZ') { - return false; - } - return true; - } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - scopes = this.__get(node); - if (!scopes || scopes.length === 0) { - return null; - } +var Syntax = require("estraverse").Syntax; +var esrecurse = require("esrecurse"); - // Heuristic selection from all scopes. - // If you would like to get all scopes, please use ScopeManager#acquireAll. - if (scopes.length === 1) { - return scopes[0]; - } +/** + * Get last array element + * @param {array} xs - array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs[xs.length - 1] || null; +} - if (inner) { - for (i = scopes.length - 1; i >= 0; --i) { - scope = scopes[i]; - if (predicate(scope)) { - return scope; - } - } - } else { - for (i = 0, iz = scopes.length; i < iz; ++i) { - scope = scopes[i]; - if (predicate(scope)) { - return scope; - } - } - } +var PatternVisitor = function (_esrecurse$Visitor) { + _inherits(PatternVisitor, _esrecurse$Visitor); - return null; + _createClass(PatternVisitor, null, [{ + key: "isPattern", + value: function isPattern(node) { + var nodeType = node.type; + + return nodeType === Syntax.Identifier || nodeType === Syntax.ObjectPattern || nodeType === Syntax.ArrayPattern || nodeType === Syntax.SpreadElement || nodeType === Syntax.RestElement || nodeType === Syntax.AssignmentPattern; } + }]); - /** - * acquire all scopes from node. - * @method ScopeManager#acquireAll - * @param {Esprima.Node} node - node for the acquired scope. - * @return {Scope[]?} - */ + function PatternVisitor(options, rootPattern, callback) { + _classCallCheck(this, PatternVisitor); - }, { - key: 'acquireAll', - value: function acquireAll(node) { - return this.__get(node); - } + var _this = _possibleConstructorReturn(this, (PatternVisitor.__proto__ || Object.getPrototypeOf(PatternVisitor)).call(this, null, options)); - /** - * release the node. - * @method ScopeManager#release - * @param {Esprima.Node} node - releasing node. - * @param {boolean=} inner - look up the most inner scope, default value is false. - * @return {Scope?} upper scope for the node. - */ + _this.rootPattern = rootPattern; + _this.callback = callback; + _this.assignments = []; + _this.rightHandNodes = []; + _this.restElements = []; + return _this; + } - }, { - key: 'release', - value: function release(node, inner) { - var scopes, scope; - scopes = this.__get(node); - if (scopes && scopes.length) { - scope = scopes[0].upper; - if (!scope) { - return null; - } - return this.acquire(scope.block, inner); - } - return null; + _createClass(PatternVisitor, [{ + key: "Identifier", + value: function Identifier(pattern) { + var lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern, + assignments: this.assignments + }); } }, { - key: 'attach', - value: function attach() {} - }, { - key: 'detach', - value: function detach() {} - }, { - key: '__nestScope', - value: function __nestScope(scope) { - if (scope instanceof _scope.GlobalScope) { - (0, _assert2.default)(this.__currentScope === null); - this.globalScope = scope; + key: "Property", + value: function Property(property) { + + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); } - this.__currentScope = scope; - return scope; - } - }, { - key: '__nestGlobalScope', - value: function __nestGlobalScope(node) { - return this.__nestScope(new _scope.GlobalScope(this, node)); + + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); } }, { - key: '__nestBlockScope', - value: function __nestBlockScope(node, isMethodDefinition) { - return this.__nestScope(new _scope.BlockScope(this, this.__currentScope, node)); + key: "ArrayPattern", + value: function ArrayPattern(pattern) { + for (var i = 0, iz = pattern.elements.length; i < iz; ++i) { + var element = pattern.elements[i]; + + this.visit(element); + } } }, { - key: '__nestFunctionScope', - value: function __nestFunctionScope(node, isMethodDefinition) { - return this.__nestScope(new _scope.FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + key: "AssignmentPattern", + value: function AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); } }, { - key: '__nestForScope', - value: function __nestForScope(node) { - return this.__nestScope(new _scope.ForScope(this, this.__currentScope, node)); + key: "RestElement", + value: function RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); } }, { - key: '__nestCatchScope', - value: function __nestCatchScope(node) { - return this.__nestScope(new _scope.CatchScope(this, this.__currentScope, node)); + key: "MemberExpression", + value: function MemberExpression(node) { + + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); } + + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // + }, { - key: '__nestWithScope', - value: function __nestWithScope(node) { - return this.__nestScope(new _scope.WithScope(this, this.__currentScope, node)); + key: "SpreadElement", + value: function SpreadElement(node) { + this.visit(node.argument); } }, { - key: '__nestClassScope', - value: function __nestClassScope(node) { - return this.__nestScope(new _scope.ClassScope(this, this.__currentScope, node)); + key: "ArrayExpression", + value: function ArrayExpression(node) { + node.elements.forEach(this.visit, this); } }, { - key: '__nestSwitchScope', - value: function __nestSwitchScope(node) { - return this.__nestScope(new _scope.SwitchScope(this, this.__currentScope, node)); + key: "AssignmentExpression", + value: function AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); } }, { - key: '__nestModuleScope', - value: function __nestModuleScope(node) { - return this.__nestScope(new _scope.ModuleScope(this, this.__currentScope, node)); - } - }, { - key: '__nestTDZScope', - value: function __nestTDZScope(node) { - return this.__nestScope(new _scope.TDZScope(this, this.__currentScope, node)); - } - }, { - key: '__nestFunctionExpressionNameScope', - value: function __nestFunctionExpressionNameScope(node) { - return this.__nestScope(new _scope.FunctionExpressionNameScope(this, this.__currentScope, node)); - } - }, { - key: '__isES6', - value: function __isES6() { - return this.__options.ecmaVersion >= 6; + key: "CallExpression", + value: function CallExpression(node) { + var _this2 = this; + + // arguments are right hand nodes. + node.arguments.forEach(function (a) { + _this2.rightHandNodes.push(a); + }); + this.visit(node.callee); } }]); - return ScopeManager; -}(); + return PatternVisitor; +}(esrecurse.Visitor); + +module.exports = PatternVisitor; /* vim: set sw=4 ts=4 et tw=80 : */ +},{"esrecurse":69,"estraverse":71}],61:[function(require,module,exports){ +/* + Copyright (C) 2015 Yusuke Suzuki -exports.default = ScopeManager; + 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. -},{"./scope":85,"assert":5,"es6-weak-map":75}],85:[function(require,module,exports){ -'use strict'; + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.ClassScope = exports.ForScope = exports.FunctionScope = exports.SwitchScope = exports.BlockScope = exports.TDZScope = exports.WithScope = exports.CatchScope = exports.FunctionExpressionNameScope = exports.ModuleScope = exports.GlobalScope = undefined; +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); -var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* - Copyright (C) 2015 Yusuke Suzuki - - 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 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. - */ +var READ = 0x1; +var WRITE = 0x2; +var RW = READ | WRITE; -var _estraverse = require('estraverse'); +/** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ -var _es6Map = require('es6-map'); +var Reference = function () { + function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + _classCallCheck(this, Reference); -var _es6Map2 = _interopRequireDefault(_es6Map); + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; -var _reference = require('./reference'); + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; -var _reference2 = _interopRequireDefault(_reference); + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; -var _variable = require('./variable'); + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; -var _variable2 = _interopRequireDefault(_variable); + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { -var _definition = require('./definition'); + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; -var _definition2 = _interopRequireDefault(_definition); + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; -var _assert = require('assert'); + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } -var _assert2 = _interopRequireDefault(_assert); + /** + * Whether the reference is static. + * @method Reference#isStatic + * @returns {boolean} static + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + _createClass(Reference, [{ + key: "isStatic", + value: function isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @returns {boolean} write + */ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + }, { + key: "isWrite", + value: function isWrite() { + return !!(this.flag & Reference.WRITE); + } -function isStrictScope(scope, block, isMethodDefinition, useDirective) { - var body, i, iz, stmt, expr; + /** + * Whether the reference is readable. + * @method Reference#isRead + * @returns {boolean} read + */ - // When upper scope is exists and strict, inner scope is also strict. - if (scope.upper && scope.upper.isStrict) { - return true; + }, { + key: "isRead", + value: function isRead() { + return !!(this.flag & Reference.READ); } - // ArrowFunctionExpression's scope is always strict scope. - if (block.type === _estraverse.Syntax.ArrowFunctionExpression) { - return true; - } + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @returns {boolean} read only + */ - if (isMethodDefinition) { - return true; + }, { + key: "isReadOnly", + value: function isReadOnly() { + return this.flag === Reference.READ; } - if (scope.type === 'class' || scope.type === 'module') { - return true; - } + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @returns {boolean} write only + */ - if (scope.type === 'block' || scope.type === 'switch') { - return false; + }, { + key: "isWriteOnly", + value: function isWriteOnly() { + return this.flag === Reference.WRITE; } - if (scope.type === 'function') { - if (block.type === _estraverse.Syntax.Program) { - body = block; - } else { - body = block.body; - } - } else if (scope.type === 'global') { - body = block; - } else { - return false; - } + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @returns {boolean} read write + */ - // Search 'use strict' directive. - if (useDirective) { - for (i = 0, iz = body.body.length; i < iz; ++i) { - stmt = body.body[i]; - if (stmt.type !== _estraverse.Syntax.DirectiveStatement) { - break; - } - if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') { - return true; - } - } - } else { - for (i = 0, iz = body.body.length; i < iz; ++i) { - stmt = body.body[i]; - if (stmt.type !== _estraverse.Syntax.ExpressionStatement) { - break; - } - expr = stmt.expression; - if (expr.type !== _estraverse.Syntax.Literal || typeof expr.value !== 'string') { - break; - } - if (expr.raw != null) { - if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') { - return true; - } - } else { - if (expr.value === 'use strict') { - return true; - } - } - } + }, { + key: "isReadWrite", + value: function isReadWrite() { + return this.flag === Reference.RW; } - return false; -} + }]); -function registerScope(scopeManager, scope) { - var scopes; + return Reference; +}(); - scopeManager.scopes.push(scope); +/** + * @constant Reference.READ + * @private + */ - scopes = scopeManager.__nodeToScope.get(scope.block); - if (scopes) { - scopes.push(scope); - } else { - scopeManager.__nodeToScope.set(scope.block, [scope]); - } -} -function shouldBeStatically(def) { - return def.type === _variable2.default.ClassName || def.type === _variable2.default.Variable && def.parent.kind !== 'var'; -} +Reference.READ = READ; /** - * @class Scope + * @constant Reference.WRITE + * @private */ +Reference.WRITE = WRITE; -var Scope = function () { - function Scope(scopeManager, type, upperScope, block, isMethodDefinition) { - _classCallCheck(this, Scope); +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; - /** - * One of 'TDZ', 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. - * @member {String} Scope#type - */ - this.type = type; - /** - * The scoped {@link Variable}s of this scope, as { Variable.name - * : Variable }. - * @member {Map} Scope#set - */ - this.set = new _es6Map2.default(); - /** - * The tainted variables of this scope, as { Variable.name : - * boolean }. - * @member {Map} Scope#taints */ - this.taints = new _es6Map2.default(); - /** - * Generally, through the lexical scoping of JS you can always know - * which variable an identifier in the source code refers to. There are - * a few exceptions to this rule. With 'global' and 'with' scopes you - * can only decide at runtime which variable a reference refers to. - * Moreover, if 'eval()' is used in a scope, it might introduce new - * bindings in this or its parent scopes. - * All those scopes are considered 'dynamic'. - * @member {boolean} Scope#dynamic - */ - this.dynamic = this.type === 'global' || this.type === 'with'; - /** - * A reference to the scope-defining syntax node. - * @member {esprima.Node} Scope#block - */ - this.block = block; - /** - * The {@link Reference|references} that are not resolved with this scope. - * @member {Reference[]} Scope#through - */ - this.through = []; - /** - * The scoped {@link Variable}s of this scope. In the case of a - * 'function' scope this includes the automatic argument arguments as - * its first element, as well as all further formal arguments. - * @member {Variable[]} Scope#variables - */ - this.variables = []; - /** - * Any variable {@link Reference|reference} found in this scope. This - * includes occurrences of local variables as well as variables from - * parent scopes (including the global scope). For local variables - * this also includes defining occurrences (like in a 'var' statement). - * In a 'function' scope this does not include the occurrences of the - * formal parameter in the parameter list. - * @member {Reference[]} Scope#references - */ - this.references = []; +module.exports = Reference; - /** - * For 'global' and 'function' scopes, this is a self-reference. For - * other scope types this is the variableScope value of the - * parent scope. - * @member {Scope} Scope#variableScope - */ - this.variableScope = this.type === 'global' || this.type === 'function' || this.type === 'module' ? this : upperScope.variableScope; - /** - * Whether this scope is created by a FunctionExpression. - * @member {boolean} Scope#functionExpressionScope - */ - this.functionExpressionScope = false; - /** - * Whether this is a scope that contains an 'eval()' invocation. - * @member {boolean} Scope#directCallToEvalScope - */ - this.directCallToEvalScope = false; - /** - * @member {boolean} Scope#thisFound - */ - this.thisFound = false; +/* vim: set sw=4 ts=4 et tw=80 : */ - this.__left = []; +},{}],62:[function(require,module,exports){ +/* + Copyright (C) 2015 Yusuke Suzuki - /** - * Reference to the parent {@link Scope|scope}. - * @member {Scope} Scope#upper - */ - this.upper = upperScope; - /** - * Whether 'use strict' is in effect in this scope. - * @member {boolean} Scope#isStrict - */ - this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - /** - * List of nested {@link Scope}s. - * @member {Scope[]} Scope#childScopes - */ - this.childScopes = []; - if (this.upper) { - this.upper.childScopes.push(this); - } + * 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.__declaredVariables = scopeManager.__declaredVariables; + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +"use strict"; - registerScope(scopeManager, this); +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Syntax = require("estraverse").Syntax; +var esrecurse = require("esrecurse"); +var Reference = require("./reference"); +var Variable = require("./variable"); +var PatternVisitor = require("./pattern-visitor"); +var definition = require("./definition"); +var assert = require("assert"); + +var ParameterDefinition = definition.ParameterDefinition; +var Definition = definition.Definition; + +/** + * Traverse identifier in pattern + * @param {Object} options - options + * @param {pattern} rootPattern - root pattern + * @param {Refencer} referencer - referencer + * @param {callback} callback - callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { + + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + var visitor = new PatternVisitor(options, rootPattern, callback); + + visitor.visit(rootPattern); + + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== undefined) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); } +} - _createClass(Scope, [{ - key: '__shouldStaticallyClose', - value: function __shouldStaticallyClose(scopeManager) { - return !this.dynamic || scopeManager.__isOptimistic(); - } - }, { - key: '__shouldStaticallyCloseForGlobal', - value: function __shouldStaticallyCloseForGlobal(ref) { - // On global scope, let/const/class declarations should be resolved statically. - var name = ref.identifier.name; - if (!this.set.has(name)) { - return false; - } +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. - var variable = this.set.get(name); - var defs = variable.defs; - return defs.length > 0 && defs.every(shouldBeStatically); +var Importer = function (_esrecurse$Visitor) { + _inherits(Importer, _esrecurse$Visitor); + + function Importer(declaration, referencer) { + _classCallCheck(this, Importer); + + var _this = _possibleConstructorReturn(this, (Importer.__proto__ || Object.getPrototypeOf(Importer)).call(this, null, referencer.options)); + + _this.declaration = declaration; + _this.referencer = referencer; + return _this; + } + + _createClass(Importer, [{ + key: "visitImport", + value: function visitImport(id, specifier) { + var _this2 = this; + + this.referencer.visitPattern(id, function (pattern) { + _this2.referencer.currentScope().__define(pattern, new Definition(Variable.ImportBinding, pattern, specifier, _this2.declaration, null, null)); + }); } }, { - key: '__staticCloseRef', - value: function __staticCloseRef(ref) { - if (!this.__resolve(ref)) { - this.__delegateToUpperScope(ref); + key: "ImportNamespaceSpecifier", + value: function ImportNamespaceSpecifier(node) { + var local = node.local || node.id; + + if (local) { + this.visitImport(local, node); } } }, { - key: '__dynamicCloseRef', - value: function __dynamicCloseRef(ref) { - // notify all names are through to global - var current = this; - do { - current.through.push(ref); - current = current.upper; - } while (current); + key: "ImportDefaultSpecifier", + value: function ImportDefaultSpecifier(node) { + var local = node.local || node.id; + + this.visitImport(local, node); } }, { - key: '__globalCloseRef', - value: function __globalCloseRef(ref) { - // let/const/class declarations should be resolved statically. - // others should be resolved dynamically. - if (this.__shouldStaticallyCloseForGlobal(ref)) { - this.__staticCloseRef(ref); + key: "ImportSpecifier", + value: function ImportSpecifier(node) { + var local = node.local || node.id; + + if (node.name) { + this.visitImport(node.name, node); } else { - this.__dynamicCloseRef(ref); + this.visitImport(local, node); } } - }, { - key: '__close', - value: function __close(scopeManager) { - var closeRef; - if (this.__shouldStaticallyClose(scopeManager)) { - closeRef = this.__staticCloseRef; - } else if (this.type !== 'global') { - closeRef = this.__dynamicCloseRef; - } else { - closeRef = this.__globalCloseRef; - } + }]); - // Try Resolving all references in this scope. - for (var i = 0, iz = this.__left.length; i < iz; ++i) { - var ref = this.__left[i]; - closeRef.call(this, ref); - } - this.__left = null; + return Importer; +}(esrecurse.Visitor); - return this.upper; +// Referencing variables and creating bindings. + + +var Referencer = function (_esrecurse$Visitor2) { + _inherits(Referencer, _esrecurse$Visitor2); + + function Referencer(options, scopeManager) { + _classCallCheck(this, Referencer); + + var _this3 = _possibleConstructorReturn(this, (Referencer.__proto__ || Object.getPrototypeOf(Referencer)).call(this, null, options)); + + _this3.options = options; + _this3.scopeManager = scopeManager; + _this3.parent = null; + _this3.isInnerMethodDefinition = false; + return _this3; + } + + _createClass(Referencer, [{ + key: "currentScope", + value: function currentScope() { + return this.scopeManager.__currentScope; } }, { - key: '__resolve', - value: function __resolve(ref) { - var variable, name; - name = ref.identifier.name; - if (this.set.has(name)) { - variable = this.set.get(name); - variable.references.push(ref); - variable.stack = variable.stack && ref.from.variableScope === this.variableScope; - if (ref.tainted) { - variable.tainted = true; - this.taints.set(variable.name, true); - } - ref.resolved = variable; - return true; + key: "close", + value: function close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); } - return false; } }, { - key: '__delegateToUpperScope', - value: function __delegateToUpperScope(ref) { - if (this.upper) { - this.upper.__left.push(ref); - } - this.through.push(ref); + key: "pushInnerMethodDefinition", + value: function pushInnerMethodDefinition(isInnerMethodDefinition) { + var previous = this.isInnerMethodDefinition; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; } }, { - key: '__addDeclaredVariablesOfNode', - value: function __addDeclaredVariablesOfNode(variable, node) { - if (node == null) { - return; - } - - var variables = this.__declaredVariables.get(node); - if (variables == null) { - variables = []; - this.__declaredVariables.set(node, variables); - } - if (variables.indexOf(variable) === -1) { - variables.push(variable); - } + key: "popInnerMethodDefinition", + value: function popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; } }, { - key: '__defineGeneric', - value: function __defineGeneric(name, set, variables, node, def) { - var variable; + key: "materializeTDZScope", + value: function materializeTDZScope(node, iterationNode) { - variable = set.get(name); - if (!variable) { - variable = new _variable2.default(name, this); - set.set(name, variable); - variables.push(variable); - } - - if (def) { - variable.defs.push(def); - if (def.type !== _variable2.default.TDZ) { - this.__addDeclaredVariablesOfNode(variable, def.node); - this.__addDeclaredVariablesOfNode(variable, def.parent); - } - } - if (node) { - variable.identifiers.push(node); - } - } - }, { - key: '__define', - value: function __define(node, def) { - if (node && node.type === _estraverse.Syntax.Identifier) { - this.__defineGeneric(node.name, this.set, this.variables, node, def); - } + // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation + // TDZ scope hides the declaration's names. + this.scopeManager.__nestTDZScope(node, iterationNode); + this.visitVariableDeclaration(this.currentScope(), Variable.TDZ, iterationNode.left, 0, true); } }, { - key: '__referencing', - value: function __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { - // because Array element may be null - if (!node || node.type !== _estraverse.Syntax.Identifier) { - return; - } + key: "materializeIterationScope", + value: function materializeIterationScope(node) { + var _this4 = this; - // Specially handle like `this`. - if (node.name === 'super') { - return; - } + // Generate iteration scope for upper ForIn/ForOf Statements. + var letOrConstDecl = node.left; - var ref = new _reference2.default(node, this, assign || _reference2.default.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); - this.references.push(ref); - this.__left.push(ref); - } - }, { - key: '__detectEval', - value: function __detectEval() { - var current; - current = this; - this.directCallToEvalScope = true; - do { - current.dynamic = true; - current = current.upper; - } while (current); - } - }, { - key: '__detectThis', - value: function __detectThis() { - this.thisFound = true; + this.scopeManager.__nestForScope(node); + this.visitVariableDeclaration(this.currentScope(), Variable.Variable, letOrConstDecl, 0); + this.visitPattern(letOrConstDecl.declarations[0].id, function (pattern) { + _this4.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); } }, { - key: '__isClosed', - value: function __isClosed() { - return this.__left === null; - } - - /** - * returns resolved {Reference} - * @method Scope#resolve - * @param {Esprima.Identifier} ident - identifier to be resolved. - * @return {Reference} - */ + key: "referencingDefaultValue", + value: function referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + var scope = this.currentScope(); + assignments.forEach(function (assignment) { + scope.__referencing(pattern, Reference.WRITE, assignment.right, maybeImplicitGlobal, pattern !== assignment.left, init); + }); + } }, { - key: 'resolve', - value: function resolve(ident) { - var ref, i, iz; - (0, _assert2.default)(this.__isClosed(), 'Scope should be closed.'); - (0, _assert2.default)(ident.type === _estraverse.Syntax.Identifier, 'Target should be identifier.'); - for (i = 0, iz = this.references.length; i < iz; ++i) { - ref = this.references[i]; - if (ref.identifier === ident) { - return ref; - } + key: "visitPattern", + value: function visitPattern(node, options, callback) { + if (typeof options === "function") { + callback = options; + options = { processRightHandNodes: false }; } - return null; + traverseIdentifierInPattern(this.options, node, options.processRightHandNodes ? this : null, callback); } - - /** - * returns this scope is static - * @method Scope#isStatic - * @return {boolean} - */ - }, { - key: 'isStatic', - value: function isStatic() { - return !this.dynamic; - } + key: "visitFunction", + value: function visitFunction(node) { + var _this5 = this; - /** - * returns this scope has materialized arguments - * @method Scope#isArgumentsMaterialized - * @return {boolean} - */ + var i = void 0, + iz = void 0; - }, { - key: 'isArgumentsMaterialized', - value: function isArgumentsMaterialized() { - return true; - } + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. - /** - * returns this scope has materialized `this` reference - * @method Scope#isThisMaterialized - * @return {boolean} - */ + if (node.type === Syntax.FunctionDeclaration) { - }, { - key: 'isThisMaterialized', - value: function isThisMaterialized() { - return true; - } - }, { - key: 'isUsedName', - value: function isUsedName(name) { - if (this.set.has(name)) { - return true; + // id is defined in upper scope + this.currentScope().__define(node.id, new Definition(Variable.FunctionName, node.id, node, null, null, null)); } - for (var i = 0, iz = this.through.length; i < iz; ++i) { - if (this.through[i].identifier.name === name) { - return true; - } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); } - return false; - } - }]); - return Scope; -}(); + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); -exports.default = Scope; + var that = this; -var GlobalScope = exports.GlobalScope = function (_Scope) { - _inherits(GlobalScope, _Scope); + /** + * Visit pattern callback + * @param {pattern} pattern - pattern + * @param {Object} info - info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, new ParameterDefinition(pattern, node, i, info.rest)); - function GlobalScope(scopeManager, block) { - _classCallCheck(this, GlobalScope); + that.referencingDefaultValue(pattern, info.assignments, null, true); + } - var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(GlobalScope).call(this, scopeManager, 'global', null, block, false)); + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } - _this.implicit = { - set: new _es6Map2.default(), - variables: [], - /** - * List of {@link Reference}s that are left to be resolved (i.e. which - * need to be linked to the variable they refer to). - * @member {Reference[]} Scope#implicit#left - */ - left: [] - }; - return _this; - } + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, function (pattern) { + _this5.currentScope().__define(pattern, new ParameterDefinition(pattern, node, node.params.length, true)); + }); + } - _createClass(GlobalScope, [{ - key: '__close', - value: function __close(scopeManager) { - var implicit = []; - for (var i = 0, iz = this.__left.length; i < iz; ++i) { - var ref = this.__left[i]; - if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { - implicit.push(ref.__maybeImplicitGlobal); + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); } } - // create an implicit global variable from assignment expression - for (var _i = 0, _iz = implicit.length; _i < _iz; ++_i) { - var info = implicit[_i]; - this.__defineImplicit(info.pattern, new _definition2.default(_variable2.default.ImplicitGlobalVariable, info.pattern, info.node, null, null, null)); + this.close(node); + } + }, { + key: "visitClass", + value: function visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, new Definition(Variable.ClassName, node.id, node, null, null, null)); } - this.implicit.left = this.__left; + // FIXME: Maybe consider TDZ. + this.visit(node.superClass); - return _get(Object.getPrototypeOf(GlobalScope.prototype), '__close', this).call(this, scopeManager); - } - }, { - key: '__defineImplicit', - value: function __defineImplicit(node, def) { - if (node && node.type === _estraverse.Syntax.Identifier) { - this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, def); + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, new Definition(Variable.ClassName, node.id, node)); } - } - }]); + this.visit(node.body); - return GlobalScope; -}(Scope); + this.close(node); + } + }, { + key: "visitProperty", + value: function visitProperty(node) { + var previous = void 0; -var ModuleScope = exports.ModuleScope = function (_Scope2) { - _inherits(ModuleScope, _Scope2); + if (node.computed) { + this.visit(node.key); + } - function ModuleScope(scopeManager, upperScope, block) { - _classCallCheck(this, ModuleScope); + var isMethodDefinition = node.type === Syntax.MethodDefinition; - return _possibleConstructorReturn(this, Object.getPrototypeOf(ModuleScope).call(this, scopeManager, 'module', upperScope, block, false)); - } + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + }, { + key: "visitForIn", + value: function visitForIn(node) { + var _this6 = this; - return ModuleScope; -}(Scope); + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.materializeTDZScope(node.right, node); + this.visit(node.right); + this.close(node.right); -var FunctionExpressionNameScope = exports.FunctionExpressionNameScope = function (_Scope3) { - _inherits(FunctionExpressionNameScope, _Scope3); + this.materializeIterationScope(node); + this.visit(node.body); + this.close(node); + } else { + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, function (pattern) { + _this6.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, function (pattern, info) { + var maybeImplicitGlobal = null; - function FunctionExpressionNameScope(scopeManager, upperScope, block) { - _classCallCheck(this, FunctionExpressionNameScope); + if (!_this6.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern: pattern, + node: node + }; + } + _this6.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + _this6.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); + } + } + }, { + key: "visitVariableDeclaration", + value: function visitVariableDeclaration(variableTargetScope, type, node, index, fromTDZ) { + var _this7 = this; - var _this3 = _possibleConstructorReturn(this, Object.getPrototypeOf(FunctionExpressionNameScope).call(this, scopeManager, 'function-expression-name', upperScope, block, false)); + // If this was called to initialize a TDZ scope, this needs to make definitions, but doesn't make references. + var decl = node.declarations[index]; + var init = decl.init; - _this3.__define(block.id, new _definition2.default(_variable2.default.FunctionName, block.id, block, null, null, null)); - _this3.functionExpressionScope = true; - return _this3; - } + this.visitPattern(decl.id, { processRightHandNodes: !fromTDZ }, function (pattern, info) { + variableTargetScope.__define(pattern, new Definition(type, pattern, decl, node, index, node.kind)); - return FunctionExpressionNameScope; -}(Scope); + if (!fromTDZ) { + _this7.referencingDefaultValue(pattern, info.assignments, null, true); + } + if (init) { + _this7.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } + }, { + key: "AssignmentExpression", + value: function AssignmentExpression(node) { + var _this8 = this; -var CatchScope = exports.CatchScope = function (_Scope4) { - _inherits(CatchScope, _Scope4); + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, function (pattern, info) { + var maybeImplicitGlobal = null; - function CatchScope(scopeManager, upperScope, block) { - _classCallCheck(this, CatchScope); + if (!_this8.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern: pattern, + node: node + }; + } + _this8.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + _this8.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + }, { + key: "CatchClause", + value: function CatchClause(node) { + var _this9 = this; - return _possibleConstructorReturn(this, Object.getPrototypeOf(CatchScope).call(this, scopeManager, 'catch', upperScope, block, false)); - } + this.scopeManager.__nestCatchScope(node); - return CatchScope; -}(Scope); + this.visitPattern(node.param, { processRightHandNodes: true }, function (pattern, info) { + _this9.currentScope().__define(pattern, new Definition(Variable.CatchClause, node.param, node, null, null, null)); + _this9.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); -var WithScope = exports.WithScope = function (_Scope5) { - _inherits(WithScope, _Scope5); + this.close(node); + } + }, { + key: "Program", + value: function Program(node) { + this.scopeManager.__nestGlobalScope(node); - function WithScope(scopeManager, upperScope, block) { - _classCallCheck(this, WithScope); + if (this.scopeManager.__isNodejsScope()) { - return _possibleConstructorReturn(this, Object.getPrototypeOf(WithScope).call(this, scopeManager, 'with', upperScope, block, false)); - } + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } - _createClass(WithScope, [{ - key: '__close', - value: function __close(scopeManager) { - if (this.__shouldStaticallyClose(scopeManager)) { - return _get(Object.getPrototypeOf(WithScope.prototype), '__close', this).call(this, scopeManager); + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); } - for (var i = 0, iz = this.__left.length; i < iz; ++i) { - var ref = this.__left[i]; - ref.tainted = true; - this.__delegateToUpperScope(ref); + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; } - this.__left = null; - return this.upper; + this.visitChildren(node); + this.close(node); } - }]); + }, { + key: "Identifier", + value: function Identifier(node) { + this.currentScope().__referencing(node); + } + }, { + key: "UpdateExpression", + value: function UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + }, { + key: "MemberExpression", + value: function MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + }, { + key: "Property", + value: function Property(node) { + this.visitProperty(node); + } + }, { + key: "MethodDefinition", + value: function MethodDefinition(node) { + this.visitProperty(node); + } + }, { + key: "BreakStatement", + value: function BreakStatement() {} // eslint-disable-line class-methods-use-this - return WithScope; -}(Scope); + }, { + key: "ContinueStatement", + value: function ContinueStatement() {} // eslint-disable-line class-methods-use-this -var TDZScope = exports.TDZScope = function (_Scope6) { - _inherits(TDZScope, _Scope6); + }, { + key: "LabeledStatement", + value: function LabeledStatement(node) { + this.visit(node.body); + } + }, { + key: "ForStatement", + value: function ForStatement(node) { - function TDZScope(scopeManager, upperScope, block) { - _classCallCheck(this, TDZScope); + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } - return _possibleConstructorReturn(this, Object.getPrototypeOf(TDZScope).call(this, scopeManager, 'TDZ', upperScope, block, false)); - } + this.visitChildren(node); - return TDZScope; -}(Scope); + this.close(node); + } + }, { + key: "ClassExpression", + value: function ClassExpression(node) { + this.visitClass(node); + } + }, { + key: "ClassDeclaration", + value: function ClassDeclaration(node) { + this.visitClass(node); + } + }, { + key: "CallExpression", + value: function CallExpression(node) { -var BlockScope = exports.BlockScope = function (_Scope7) { - _inherits(BlockScope, _Scope7); + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { - function BlockScope(scopeManager, upperScope, block) { - _classCallCheck(this, BlockScope); + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + }, { + key: "BlockStatement", + value: function BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } - return _possibleConstructorReturn(this, Object.getPrototypeOf(BlockScope).call(this, scopeManager, 'block', upperScope, block, false)); - } + this.visitChildren(node); - return BlockScope; -}(Scope); + this.close(node); + } + }, { + key: "ThisExpression", + value: function ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + }, { + key: "WithStatement", + value: function WithStatement(node) { + this.visit(node.object); -var SwitchScope = exports.SwitchScope = function (_Scope8) { - _inherits(SwitchScope, _Scope8); + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); - function SwitchScope(scopeManager, upperScope, block) { - _classCallCheck(this, SwitchScope); + this.visit(node.body); - return _possibleConstructorReturn(this, Object.getPrototypeOf(SwitchScope).call(this, scopeManager, 'switch', upperScope, block, false)); - } + this.close(node); + } + }, { + key: "VariableDeclaration", + value: function VariableDeclaration(node) { + var variableTargetScope = node.kind === "var" ? this.currentScope().variableScope : this.currentScope(); - return SwitchScope; -}(Scope); + for (var i = 0, iz = node.declarations.length; i < iz; ++i) { + var decl = node.declarations[i]; -var FunctionScope = exports.FunctionScope = function (_Scope9) { - _inherits(FunctionScope, _Scope9); + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } - function FunctionScope(scopeManager, upperScope, block, isMethodDefinition) { - _classCallCheck(this, FunctionScope); + // sec 13.11.8 - // section 9.2.13, FunctionDeclarationInstantiation. - // NOTE Arrow functions never have an arguments objects. + }, { + key: "SwitchStatement", + value: function SwitchStatement(node) { + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } - var _this9 = _possibleConstructorReturn(this, Object.getPrototypeOf(FunctionScope).call(this, scopeManager, 'function', upperScope, block, isMethodDefinition)); + for (var i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } - if (_this9.block.type !== _estraverse.Syntax.ArrowFunctionExpression) { - _this9.__defineArguments(); + this.close(node); } - return _this9; - } + }, { + key: "FunctionDeclaration", + value: function FunctionDeclaration(node) { + this.visitFunction(node); + } + }, { + key: "FunctionExpression", + value: function FunctionExpression(node) { + this.visitFunction(node); + } + }, { + key: "ForOfStatement", + value: function ForOfStatement(node) { + this.visitForIn(node); + } + }, { + key: "ForInStatement", + value: function ForInStatement(node) { + this.visitForIn(node); + } + }, { + key: "ArrowFunctionExpression", + value: function ArrowFunctionExpression(node) { + this.visitFunction(node); + } + }, { + key: "ImportDeclaration", + value: function ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); - _createClass(FunctionScope, [{ - key: 'isArgumentsMaterialized', - value: function isArgumentsMaterialized() { - // TODO(Constellation) - // We can more aggressive on this condition like this. - // - // function t() { - // // arguments of t is always hidden. - // function arguments() { - // } - // } - if (this.block.type === _estraverse.Syntax.ArrowFunctionExpression) { - return false; - } + var importer = new Importer(node, this); - if (!this.isStatic()) { - return true; + importer.visit(node); + } + }, { + key: "visitExportDeclaration", + value: function visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; } - var variable = this.set.get('arguments'); - (0, _assert2.default)(variable, 'Always have arguments variable.'); - return variable.tainted || variable.references.length !== 0; + this.visitChildren(node); } }, { - key: 'isThisMaterialized', - value: function isThisMaterialized() { - if (!this.isStatic()) { - return true; - } - return this.thisFound; + key: "ExportDeclaration", + value: function ExportDeclaration(node) { + this.visitExportDeclaration(node); } }, { - key: '__defineArguments', - value: function __defineArguments() { - this.__defineGeneric('arguments', this.set, this.variables, null, null); - this.taints.set('arguments', true); + key: "ExportNamedDeclaration", + value: function ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); } - }]); + }, { + key: "ExportSpecifier", + value: function ExportSpecifier(node) { + var local = node.id || node.local; - return FunctionScope; -}(Scope); + this.visit(local); + } + }, { + key: "MetaProperty", + value: function MetaProperty() {// eslint-disable-line class-methods-use-this -var ForScope = exports.ForScope = function (_Scope10) { - _inherits(ForScope, _Scope10); + // do nothing. + } + }]); - function ForScope(scopeManager, upperScope, block) { - _classCallCheck(this, ForScope); - - return _possibleConstructorReturn(this, Object.getPrototypeOf(ForScope).call(this, scopeManager, 'for', upperScope, block, false)); - } - - return ForScope; -}(Scope); - -var ClassScope = exports.ClassScope = function (_Scope11) { - _inherits(ClassScope, _Scope11); - - function ClassScope(scopeManager, upperScope, block) { - _classCallCheck(this, ClassScope); - - return _possibleConstructorReturn(this, Object.getPrototypeOf(ClassScope).call(this, scopeManager, 'class', upperScope, block, false)); - } + return Referencer; +}(esrecurse.Visitor); - return ClassScope; -}(Scope); +module.exports = Referencer; /* vim: set sw=4 ts=4 et tw=80 : */ - -},{"./definition":79,"./reference":82,"./variable":86,"assert":5,"es6-map":64,"estraverse":92}],86:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - +},{"./definition":58,"./pattern-visitor":60,"./reference":61,"./variable":65,"assert":47,"esrecurse":69,"estraverse":71}],63:[function(require,module,exports){ /* Copyright (C) 2015 Yusuke Suzuki @@ -21261,1992 +24378,1856 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +"use strict"; -/** - * A Variable represents a locally scoped identifier. These include arguments to - * functions. - * @class Variable - */ - -var Variable = function Variable(name, scope) { - _classCallCheck(this, Variable); - - /** - * The variable name, as given in the source code. - * @member {String} Variable#name - */ - this.name = name; - /** - * List of defining occurrences of this variable (like in 'var ...' - * statements or as parameter), as AST nodes. - * @member {esprima.Identifier[]} Variable#identifiers - */ - this.identifiers = []; - /** - * List of {@link Reference|references} of this variable (excluding parameter entries) - * in its defining scope and all nested scopes. For defining - * occurrences only see {@link Variable#defs}. - * @member {Reference[]} Variable#references - */ - this.references = []; - - /** - * List of defining occurrences of this variable (like in 'var ...' - * statements or as parameter), as custom objects. - * @member {Definition[]} Variable#defs - */ - this.defs = []; +/* eslint-disable no-underscore-dangle */ - this.tainted = false; - /** - * Whether this is a stack variable. - * @member {boolean} Variable#stack - */ - this.stack = true; - /** - * Reference to the enclosing Scope. - * @member {Scope} Variable#scope - */ - this.scope = scope; -}; +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); -exports.default = Variable; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +var Scope = require("./scope"); +var assert = require("assert"); -Variable.CatchClause = 'CatchClause'; -Variable.Parameter = 'Parameter'; -Variable.FunctionName = 'FunctionName'; -Variable.ClassName = 'ClassName'; -Variable.Variable = 'Variable'; -Variable.ImportBinding = 'ImportBinding'; -Variable.TDZ = 'TDZ'; -Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable'; +var GlobalScope = Scope.GlobalScope; +var CatchScope = Scope.CatchScope; +var WithScope = Scope.WithScope; +var ModuleScope = Scope.ModuleScope; +var ClassScope = Scope.ClassScope; +var SwitchScope = Scope.SwitchScope; +var FunctionScope = Scope.FunctionScope; +var ForScope = Scope.ForScope; +var TDZScope = Scope.TDZScope; +var FunctionExpressionNameScope = Scope.FunctionExpressionNameScope; +var BlockScope = Scope.BlockScope; -/* vim: set sw=4 ts=4 et tw=80 : */ +/** + * @class ScopeManager + */ +var ScopeManager = function () { + function ScopeManager(options) { + _classCallCheck(this, ScopeManager); -},{}],87:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "escope@^3.6.0", - "scope": null, - "escapedName": "escope", - "name": "escope", - "rawSpec": "^3.6.0", - "spec": ">=3.6.0 <4.0.0", - "type": "range" - }, - "D:\\users\\r2g\\exps\\eslint-3.19.0" - ] - ], - "_from": "escope@>=3.6.0 <4.0.0", - "_id": "escope@3.6.0", - "_inCache": true, - "_location": "/escope", - "_nodeVersion": "0.12.9", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/escope-3.6.0.tgz_1457720018969_0.025237560039386153" - }, - "_npmUser": { - "name": "nzakas", - "email": "nicholas@nczconsulting.com" - }, - "_npmVersion": "2.14.9", - "_phantomChildren": {}, - "_requested": { - "raw": "escope@^3.6.0", - "scope": null, - "escapedName": "escope", - "name": "escope", - "rawSpec": "^3.6.0", - "spec": ">=3.6.0 <4.0.0", - "type": "range" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/escope/-/escope-3.6.0.tgz", - "_shasum": "e01975e812781a163a6dadfdd80398dc64c889c3", - "_shrinkwrap": null, - "_spec": "escope@^3.6.0", - "_where": "D:\\users\\r2g\\exps\\eslint-3.19.0", - "bugs": { - "url": "https://github.com/estools/escope/issues" - }, - "dependencies": { - "es6-map": "^0.1.3", - "es6-weak-map": "^2.0.1", - "esrecurse": "^4.1.0", - "estraverse": "^4.1.1" - }, - "description": "ECMAScript scope analyzer", - "devDependencies": { - "babel": "^6.3.26", - "babel-preset-es2015": "^6.3.13", - "babel-register": "^6.3.13", - "browserify": "^13.0.0", - "chai": "^3.4.1", - "espree": "^3.1.1", - "esprima": "^2.7.1", - "gulp": "^3.9.0", - "gulp-babel": "^6.1.1", - "gulp-bump": "^1.0.0", - "gulp-eslint": "^1.1.1", - "gulp-espower": "^1.0.2", - "gulp-filter": "^3.0.1", - "gulp-git": "^1.6.1", - "gulp-mocha": "^2.2.0", - "gulp-plumber": "^1.0.1", - "gulp-sourcemaps": "^1.6.0", - "gulp-tag-version": "^1.3.0", - "jsdoc": "^3.4.0", - "lazypipe": "^1.0.1", - "vinyl-source-stream": "^1.1.0" - }, - "directories": {}, - "dist": { - "shasum": "e01975e812781a163a6dadfdd80398dc64c889c3", - "tarball": "https://registry.npmjs.org/escope/-/escope-3.6.0.tgz" - }, - "engines": { - "node": ">=0.4.0" - }, - "gitHead": "aa35861faa76a09f01203dee3497a939d70b463c", - "homepage": "http://github.com/estools/escope", - "license": "BSD-2-Clause", - "main": "lib/index.js", - "maintainers": [ - { - "name": "constellation", - "email": "utatane.tea@gmail.com" - }, - { - "name": "michaelficarra", - "email": "npm@michael.ficarra.me" - }, - { - "name": "nzakas", - "email": "nicholas@nczconsulting.com" + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); } - ], - "name": "escope", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/estools/escope.git" - }, - "scripts": { - "jsdoc": "jsdoc src/*.js README.md", - "lint": "gulp lint", - "test": "gulp travis", - "unit-test": "gulp test" - }, - "version": "3.6.0" -} - -},{}],88:[function(require,module,exports){ -/* vim: set sw=4 sts=4 : */ -(function () { - var estraverse = require('estraverse'); - var parser = require('./parser'); - - var isArray = Array.isArray || function isArray(array) { - return {}.toString.call(array) === '[object Array]'; - }; - - var LEFT_SIDE = {}; - var RIGHT_SIDE = {}; + _createClass(ScopeManager, [{ + key: "__useDirective", + value: function __useDirective() { + return this.__options.directive; + } + }, { + key: "__isOptimistic", + value: function __isOptimistic() { + return this.__options.optimistic; + } + }, { + key: "__ignoreEval", + value: function __ignoreEval() { + return this.__options.ignoreEval; + } + }, { + key: "__isNodejsScope", + value: function __isNodejsScope() { + return this.__options.nodejsScope; + } + }, { + key: "isModule", + value: function isModule() { + return this.__options.sourceType === "module"; + } + }, { + key: "isImpliedStrict", + value: function isImpliedStrict() { + return this.__options.impliedStrict; + } + }, { + key: "isStrictModeSupported", + value: function isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } - function esqueryModule() { + // Returns appropriate scope for this node. - /** - * Get the value of a property which may be multiple levels down in the object. - */ - function getPath(obj, key) { - var i, keys = key.split("."); - for (i = 0; i < keys.length; i++) { - if (obj == null) { return obj; } - obj = obj[keys[i]]; - } - return obj; + }, { + key: "__get", + value: function __get(node) { + return this.__nodeToScope.get(node); } /** - * Determine whether `node` can be reached by following `path`, starting at `ancestor`. + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * + * @param {Espree.Node} node - a node to get. + * @returns {Variable[]} variables that declared by the node. */ - function inPath(node, ancestor, path) { - var field, remainingPath, i; - if (path.length === 0) { return node === ancestor; } - if (ancestor == null) { return false; } - field = ancestor[path[0]]; - remainingPath = path.slice(1); - if (isArray(field)) { - for (i = 0, l = field.length; i < l; ++i) { - if (inPath(node, field[i], remainingPath)) { return true; } - } - return false; - } else { - return inPath(node, field, remainingPath); - } + + }, { + key: "getDeclaredVariables", + value: function getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; } /** - * Given a `node` and its ancestors, determine if `node` is matched by `selector`. + * acquire scope from node. + * @method ScopeManager#acquire + * @param {Espree.Node} node - node for the acquired scope. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node */ - function matches(node, selector, ancestry) { - var path, ancestor, i, l, p; - if (!selector) { return true; } - if (!node) { return false; } - if (!ancestry) { ancestry = []; } - - switch(selector.type) { - case 'wildcard': - return true; - - case 'identifier': - return selector.value.toLowerCase() === node.type.toLowerCase(); - - case 'field': - path = selector.name.split('.'); - ancestor = ancestry[path.length - 1]; - return inPath(node, ancestor, path); - - case 'matches': - for (i = 0, l = selector.selectors.length; i < l; ++i) { - if (matches(node, selector.selectors[i], ancestry)) { return true; } - } - return false; - - case 'compound': - for (i = 0, l = selector.selectors.length; i < l; ++i) { - if (!matches(node, selector.selectors[i], ancestry)) { return false; } - } - return true; - case 'not': - for (i = 0, l = selector.selectors.length; i < l; ++i) { - if (matches(node, selector.selectors[i], ancestry)) { return false; } - } - return true; + }, { + key: "acquire", + value: function acquire(node, inner) { - case 'child': - if (matches(node, selector.right, ancestry)) { - return matches(ancestry[0], selector.left, ancestry.slice(1)); - } + /** + * predicate + * @param {Scope} testScope - scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { return false; - - case 'descendant': - if (matches(node, selector.right, ancestry)) { - for (i = 0, l = ancestry.length; i < l; ++i) { - if (matches(ancestry[i], selector.left, ancestry.slice(i + 1))) { - return true; - } - } - } + } + if (testScope.type === "TDZ") { return false; + } + return true; + } - case 'attribute': - p = getPath(node, selector.name); - switch (selector.operator) { - case null: - case void 0: - return p != null; - case '=': - switch (selector.value.type) { - case 'regexp': return selector.value.value.test(p); - case 'literal': return '' + selector.value.value === '' + p; - case 'type': return selector.value.value === typeof p; - } - case '!=': - switch (selector.value.type) { - case 'regexp': return !selector.value.value.test(p); - case 'literal': return '' + selector.value.value !== '' + p; - case 'type': return selector.value.value !== typeof p; - } - case '<=': return p <= selector.value.value; - case '<': return p < selector.value.value; - case '>': return p > selector.value.value; - case '>=': return p >= selector.value.value; - } - - case 'sibling': - return matches(node, selector.right, ancestry) && - sibling(node, selector.left, ancestry, LEFT_SIDE) || - selector.left.subject && - matches(node, selector.left, ancestry) && - sibling(node, selector.right, ancestry, RIGHT_SIDE); - - case 'adjacent': - return matches(node, selector.right, ancestry) && - adjacent(node, selector.left, ancestry, LEFT_SIDE) || - selector.right.subject && - matches(node, selector.left, ancestry) && - adjacent(node, selector.right, ancestry, RIGHT_SIDE); - - case 'nth-child': - return matches(node, selector.right, ancestry) && - nthChild(node, ancestry, function (length) { - return selector.index.value - 1; - }); + var scopes = this.__get(node); - case 'nth-last-child': - return matches(node, selector.right, ancestry) && - nthChild(node, ancestry, function (length) { - return length - selector.index.value; - }); + if (!scopes || scopes.length === 0) { + return null; + } - case 'class': - if(!node.type) return false; - switch(selector.name.toLowerCase()){ - case 'statement': - if(node.type.slice(-9) === 'Statement') return true; - // fallthrough: interface Declaration <: Statement { } - case 'declaration': - return node.type.slice(-11) === 'Declaration'; - case 'pattern': - if(node.type.slice(-7) === 'Pattern') return true; - // fallthrough: interface Expression <: Node, Pattern { } - case 'expression': - return node.type.slice(-10) === 'Expression' || - node.type === 'Literal' || - node.type === 'Identifier'; - case 'function': - return node.type.slice(0, 8) === 'Function' || - node.type === 'ArrowFunctionExpression'; - } - throw new Error('Unknown class name: ' + selector.name); + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; } - throw new Error('Unknown selector type: ' + selector.type); - } + if (inner) { + for (var i = scopes.length - 1; i >= 0; --i) { + var scope = scopes[i]; - /* - * Determines if the given node has a sibling that matches the given selector. - */ - function sibling(node, selector, ancestry, side) { - var parent = ancestry[0], listProp, startIndex, keys, i, l, k, lowerBound, upperBound; - if (!parent) { return false; } - keys = estraverse.VisitorKeys[parent.type]; - for (i = 0, l = keys.length; i < l; ++i) { - listProp = parent[keys[i]]; - if (isArray(listProp)) { - startIndex = listProp.indexOf(node); - if (startIndex < 0) { continue; } - if (side === LEFT_SIDE) { - lowerBound = 0; - upperBound = startIndex; - } else { - lowerBound = startIndex + 1; - upperBound = listProp.length; + if (predicate(scope)) { + return scope; } - for (k = lowerBound; k < upperBound; ++k) { - if (matches(listProp[k], selector, ancestry)) { - return true; - } + } + } else { + for (var _i = 0, iz = scopes.length; _i < iz; ++_i) { + var _scope = scopes[_i]; + + if (predicate(_scope)) { + return _scope; } } } - return false; + + return null; } - /* - * Determines if the given node has an asjacent sibling that matches the given selector. + /** + * acquire all scopes from node. + * @method ScopeManager#acquireAll + * @param {Espree.Node} node - node for the acquired scope. + * @returns {Scopes?} Scope array */ - function adjacent(node, selector, ancestry, side) { - var parent = ancestry[0], listProp, keys, i, l, idx; - if (!parent) { return false; } - keys = estraverse.VisitorKeys[parent.type]; - for (i = 0, l = keys.length; i < l; ++i) { - listProp = parent[keys[i]]; - if (isArray(listProp)) { - idx = listProp.indexOf(node); - if (idx < 0) { continue; } - if (side === LEFT_SIDE && idx > 0 && matches(listProp[idx - 1], selector, ancestry)) { - return true; - } - if (side === RIGHT_SIDE && idx < listProp.length - 1 && matches(listProp[idx + 1], selector, ancestry)) { - return true; - } - } - } - return false; + + }, { + key: "acquireAll", + value: function acquireAll(node) { + return this.__get(node); } - /* - * Determines if the given node is the nth child, determined by idxFn, which is given the containing list's length. + /** + * release the node. + * @method ScopeManager#release + * @param {Espree.Node} node - releasing node. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. */ - function nthChild(node, ancestry, idxFn) { - var parent = ancestry[0], listProp, keys, i, l, idx; - if (!parent) { return false; } - keys = estraverse.VisitorKeys[parent.type]; - for (i = 0, l = keys.length; i < l; ++i) { - listProp = parent[keys[i]]; - if (isArray(listProp)) { - idx = listProp.indexOf(node); - if (idx >= 0 && idx === idxFn(listProp.length)) { return true; } + + }, { + key: "release", + value: function release(node, inner) { + var scopes = this.__get(node); + + if (scopes && scopes.length) { + var scope = scopes[0].upper; + + if (!scope) { + return null; } + return this.acquire(scope.block, inner); } - return false; + return null; } + }, { + key: "attach", + value: function attach() {} // eslint-disable-line class-methods-use-this - /* - * For each selector node marked as a subject, find the portion of the selector that the subject must match. - */ - function subjects(selector, ancestor) { - var results, p; - if (selector == null || typeof selector != 'object') { return []; } - if (ancestor == null) { ancestor = selector; } - results = selector.subject ? [ancestor] : []; - for(p in selector) { - if(!{}.hasOwnProperty.call(selector, p)) { continue; } - [].push.apply(results, subjects(selector[p], p === 'left' ? selector[p] : ancestor)); + }, { + key: "detach", + value: function detach() {} // eslint-disable-line class-methods-use-this + + }, { + key: "__nestScope", + value: function __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; } - return results; + this.__currentScope = scope; + return scope; } - - /** - * From a JS AST and a selector AST, collect all JS AST nodes that match the selector. - */ - function match(ast, selector) { - var ancestry = [], results = [], altSubjects, i, l, k, m; - if (!selector) { return results; } - altSubjects = subjects(selector); - estraverse.traverse(ast, { - enter: function (node, parent) { - if (parent != null) { ancestry.unshift(parent); } - if (matches(node, selector, ancestry)) { - if (altSubjects.length) { - for (i = 0, l = altSubjects.length; i < l; ++i) { - if (matches(node, altSubjects[i], ancestry)) { results.push(node); } - for (k = 0, m = ancestry.length; k < m; ++k) { - if (matches(ancestry[k], altSubjects[i], ancestry.slice(k + 1))) { - results.push(ancestry[k]); - } - } - } - } else { - results.push(node); - } - } - }, - leave: function () { ancestry.shift(); } - }); - return results; + }, { + key: "__nestGlobalScope", + value: function __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); } - - /** - * Parse a selector string and return its AST. - */ - function parse(selector) { - return parser.parse(selector); + }, { + key: "__nestBlockScope", + value: function __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); } - - /** - * Query the code AST using the selector string. - */ - function query(ast, selector) { - return match(ast, parse(selector)); + }, { + key: "__nestFunctionScope", + value: function __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + }, { + key: "__nestForScope", + value: function __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + }, { + key: "__nestCatchScope", + value: function __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + }, { + key: "__nestWithScope", + value: function __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + }, { + key: "__nestClassScope", + value: function __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + }, { + key: "__nestSwitchScope", + value: function __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + }, { + key: "__nestModuleScope", + value: function __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + }, { + key: "__nestTDZScope", + value: function __nestTDZScope(node) { + return this.__nestScope(new TDZScope(this, this.__currentScope, node)); } + }, { + key: "__nestFunctionExpressionNameScope", + value: function __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + }, { + key: "__isES6", + value: function __isES6() { + return this.__options.ecmaVersion >= 6; + } + }]); - query.parse = parse; - query.match = match; - query.matches = matches; - return query.query = query; - } + return ScopeManager; +}(); +module.exports = ScopeManager; - if (typeof define === "function" && define.amd) { - define(esqueryModule); - } else if (typeof module !== 'undefined' && module.exports) { - module.exports = esqueryModule(); - } else { - this.esquery = esqueryModule(); - } +/* vim: set sw=4 ts=4 et tw=80 : */ -})(); +},{"./scope":64,"assert":47}],64:[function(require,module,exports){ +/* + Copyright (C) 2015 Yusuke Suzuki -},{"./parser":89,"estraverse":92}],89:[function(require,module,exports){ -var result = (function(){ - /* - * Generated by PEG.js 0.7.0. - * - * http://pegjs.majda.cz/ - */ - - function quote(s) { - /* - * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a - * string literal except for the closing quote character, backslash, - * carriage return, line separator, paragraph separator, and line feed. - * Any character may appear in the form of an escape sequence. - * - * For portability, we also escape escape all control and non-ASCII - * characters. Note that "\0" and "\v" escape sequences are not used - * because JSHint does not like the first and IE the second. - */ - return '"' + s - .replace(/\\/g, '\\\\') // backslash - .replace(/"/g, '\\"') // closing quote character - .replace(/\x08/g, '\\b') // backspace - .replace(/\t/g, '\\t') // horizontal tab - .replace(/\n/g, '\\n') // line feed - .replace(/\f/g, '\\f') // form feed - .replace(/\r/g, '\\r') // carriage return - .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) - + '"'; - } - - var result = { - /* - * Parses the input with a generated parser. If the parsing is successfull, - * returns a value explicitly or implicitly specified by the grammar from - * which the parser was generated (see |PEG.buildParser|). If the parsing is - * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. - */ - parse: function(input, startRule) { - var parseFunctions = { - "start": parse_start, - "_": parse__, - "identifierName": parse_identifierName, - "binaryOp": parse_binaryOp, - "selectors": parse_selectors, - "selector": parse_selector, - "sequence": parse_sequence, - "atom": parse_atom, - "wildcard": parse_wildcard, - "identifier": parse_identifier, - "attr": parse_attr, - "attrOps": parse_attrOps, - "attrEqOps": parse_attrEqOps, - "attrName": parse_attrName, - "attrValue": parse_attrValue, - "string": parse_string, - "number": parse_number, - "path": parse_path, - "type": parse_type, - "regex": parse_regex, - "field": parse_field, - "negation": parse_negation, - "matches": parse_matches, - "firstChild": parse_firstChild, - "lastChild": parse_lastChild, - "nthChild": parse_nthChild, - "nthLastChild": parse_nthLastChild, - "class": parse_class - }; - - if (startRule !== undefined) { - if (parseFunctions[startRule] === undefined) { - throw new Error("Invalid rule name: " + quote(startRule) + "."); - } - } else { - startRule = "start"; - } - - var pos = 0; - var reportFailures = 0; - var rightmostFailuresPos = 0; - var rightmostFailuresExpected = []; - var cache = {}; - - function padLeft(input, padding, length) { - var result = input; - - var padLength = length - input.length; - for (var i = 0; i < padLength; i++) { - result = padding + result; - } - - return result; - } - - function escape(ch) { - var charCode = ch.charCodeAt(0); - var escapeChar; - var length; - - if (charCode <= 0xFF) { - escapeChar = 'x'; - length = 2; + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +"use strict"; + +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ + +var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Syntax = require("estraverse").Syntax; + +var Reference = require("./reference"); +var Variable = require("./variable"); +var Definition = require("./definition").Definition; +var assert = require("assert"); + +/** + * Test if scope is struct + * @param {Scope} scope - scope + * @param {Block} block - block + * @param {boolean} isMethodDefinition - is method definiton + * @param {boolean} useDirective - use directive + * @returns {boolean} is strict scope + */ +function isStrictScope(scope, block, isMethodDefinition, useDirective) { + var body = void 0; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + // ArrowFunctionExpression's scope is always strict scope. + if (block.type === Syntax.ArrowFunctionExpression) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === Syntax.Program) { + body = block; } else { - escapeChar = 'u'; - length = 4; - } - - return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); - } - - function matchFailed(failure) { - if (pos < rightmostFailuresPos) { - return; + body = block.body; } - - if (pos > rightmostFailuresPos) { - rightmostFailuresPos = pos; - rightmostFailuresExpected = []; + + if (!body) { + return false; } - - rightmostFailuresExpected.push(failure); - } - - function parse_start() { - var cacheKey = "start@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search 'use strict' directive. + if (useDirective) { + for (var i = 0, iz = body.body.length; i < iz; ++i) { + var stmt = body.body[i]; + + if (stmt.type !== Syntax.DirectiveStatement) { + break; + } + if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") { + return true; + } } - - var result0, result1, result2; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - result0 = parse__(); - if (result0 !== null) { - result1 = parse_selectors(); - if (result1 !== null) { - result2 = parse__(); - if (result2 !== null) { - result0 = [result0, result1, result2]; + } else { + for (var _i = 0, _iz = body.body.length; _i < _iz; ++_i) { + var _stmt = body.body[_i]; + + if (_stmt.type !== Syntax.ExpressionStatement) { + break; + } + var expr = _stmt.expression; + + if (expr.type !== Syntax.Literal || typeof expr.value !== "string") { + break; + } + if (expr.raw !== null && expr.raw !== undefined) { + if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") { + return true; + } } else { - result0 = null; - pos = pos1; + if (expr.value === "use strict") { + return true; + } } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, ss) { return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss }; })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - result0 = parse__(); - if (result0 !== null) { - result0 = (function(offset) { return void 0; })(pos0); - } - if (result0 === null) { - pos = pos0; - } } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse__() { - var cacheKey = "_@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + } + return false; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager - scope manager + * @param {Scope} scope - scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + var scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * Should be statically + * @param {Object} def - def + * @returns {boolean} should be statically + */ +function shouldBeStatically(def) { + return def.type === Variable.ClassName || def.type === Variable.Variable && def.parent.kind !== "var"; +} + +/** + * @class Scope + */ + +var Scope = function () { + function Scope(scopeManager, type, upperScope, block, isMethodDefinition) { + _classCallCheck(this, Scope); + + /** + * One of 'TDZ', 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. + * @member {String} Scope#type + */ + this.type = type; + + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); + + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; + + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = this.type === "global" || this.type === "function" || this.type === "module" ? this : upperScope.variableScope; + + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); } - - var result0, result1; - - result0 = []; - if (input.charCodeAt(pos) === 32) { - result1 = " "; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\" \""); - } + + this.__declaredVariables = scopeManager.__declaredVariables; + + registerScope(scopeManager, this); + } + + _createClass(Scope, [{ + key: "__shouldStaticallyClose", + value: function __shouldStaticallyClose(scopeManager) { + return !this.dynamic || scopeManager.__isOptimistic(); } - while (result1 !== null) { - result0.push(result1); - if (input.charCodeAt(pos) === 32) { - result1 = " "; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\" \""); + }, { + key: "__shouldStaticallyCloseForGlobal", + value: function __shouldStaticallyCloseForGlobal(ref) { + + // On global scope, let/const/class declarations should be resolved statically. + var name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; } - } + + var variable = this.set.get(name); + var defs = variable.defs; + + return defs.length > 0 && defs.every(shouldBeStatically); } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_identifierName() { - var cacheKey = "identifierName@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + }, { + key: "__staticCloseRef", + value: function __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } } - - var result0, result1; - var pos0; - - pos0 = pos; - if (/^[^ [\],():#!=><~+.]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("[^ [\\],():#!=><~+.]"); - } + }, { + key: "__dynamicCloseRef", + value: function __dynamicCloseRef(ref) { + + // notify all names are through to global + var current = this; + + do { + current.through.push(ref); + current = current.upper; + } while (current); } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - if (/^[^ [\],():#!=><~+.]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); - pos++; + }, { + key: "__globalCloseRef", + value: function __globalCloseRef(ref) { + + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("[^ [\\],():#!=><~+.]"); - } + this.__dynamicCloseRef(ref); } - } - } else { - result0 = null; } - if (result0 !== null) { - result0 = (function(offset, i) { return i.join(''); })(pos0, result0); + }, { + key: "__close", + value: function __close(scopeManager) { + var closeRef = void 0; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } + + // Try Resolving all references in this scope. + for (var i = 0, iz = this.__left.length; i < iz; ++i) { + var ref = this.__left[i]; + + closeRef.call(this, ref); + } + this.__left = null; + + return this.upper; } - if (result0 === null) { - pos = pos0; + }, { + key: "__resolve", + value: function __resolve(ref) { + var name = ref.identifier.name; + + if (this.set.has(name)) { + var variable = this.set.get(name); + + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + return true; + } + return false; } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_binaryOp() { - var cacheKey = "binaryOp@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + }, { + key: "__delegateToUpperScope", + value: function __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); } - - var result0, result1, result2; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - result0 = parse__(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 62) { - result1 = ">"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\">\""); - } - } - if (result1 !== null) { - result2 = parse__(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { return 'child'; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - pos1 = pos; - result0 = parse__(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 126) { - result1 = "~"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - if (result1 !== null) { - result2 = parse__(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { return 'sibling'; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - pos1 = pos; - result0 = parse__(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 !== null) { - result2 = parse__(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { return 'adjacent'; })(pos0); + }, { + key: "__addDeclaredVariablesOfNode", + value: function __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === undefined) { + return; } - if (result0 === null) { - pos = pos0; + + var variables = this.__declaredVariables.get(node); + + if (variables === null || variables === undefined) { + variables = []; + this.__declaredVariables.set(node, variables); } - if (result0 === null) { - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 32) { - result0 = " "; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\" \""); - } - } - if (result0 !== null) { - result1 = parse__(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { return 'descendant'; })(pos0); - } - if (result0 === null) { - pos = pos0; - } + if (variables.indexOf(variable) === -1) { + variables.push(variable); } - } - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_selectors() { - var cacheKey = "selectors@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; } - - var result0, result1, result2, result3, result4, result5; - var pos0, pos1, pos2; - - pos0 = pos; - pos1 = pos; - result0 = parse_selector(); - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse__(); - if (result2 !== null) { - if (input.charCodeAt(pos) === 44) { - result3 = ","; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } + }, { + key: "__defineGeneric", + value: function __defineGeneric(name, set, variables, node, def) { + var variable = void 0; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); } - if (result3 !== null) { - result4 = parse__(); - if (result4 !== null) { - result5 = parse_selector(); - if (result5 !== null) { - result2 = [result2, result3, result4, result5]; - } else { - result2 = null; - pos = pos2; + + if (def) { + variable.defs.push(def); + if (def.type !== Variable.TDZ) { + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); } - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse__(); - if (result2 !== null) { - if (input.charCodeAt(pos) === 44) { - result3 = ","; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result3 !== null) { - result4 = parse__(); - if (result4 !== null) { - result5 = parse_selector(); - if (result5 !== null) { - result2 = [result2, result3, result4, result5]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; + if (node) { + variable.identifiers.push(node); } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, s, ss) { - return [s].concat(ss.map(function (s) { return s[3]; })); - })(pos0, result0[0], result0[1]); - } - if (result0 === null) { - pos = pos0; } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_selector() { - var cacheKey = "selector@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + }, { + key: "__define", + value: function __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric(node.name, this.set, this.variables, node, def); + } } - - var result0, result1, result2, result3; - var pos0, pos1, pos2; - - pos0 = pos; - pos1 = pos; - result0 = parse_sequence(); - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_binaryOp(); - if (result2 !== null) { - result3 = parse_sequence(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; + }, { + key: "__referencing", + value: function __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + + // because Array element may be null + if (!node || node.type !== Syntax.Identifier) { + return; } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_binaryOp(); - if (result2 !== null) { - result3 = parse_sequence(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; + + // Specially handle like `this`. + if (node.name === "super") { + return; } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, a, ops) { - return ops.reduce(function (memo, rhs) { - return { type: rhs[0], left: memo, right: rhs[1] }; - }, a); - })(pos0, result0[0], result0[1]); + + var ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); + + this.references.push(ref); + this.__left.push(ref); } - if (result0 === null) { - pos = pos0; + }, { + key: "__detectEval", + value: function __detectEval() { + var current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_sequence() { - var cacheKey = "sequence@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + }, { + key: "__detectThis", + value: function __detectThis() { + this.thisFound = true; } - - var result0, result1, result2; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 33) { - result0 = "!"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } + }, { + key: "__isClosed", + value: function __isClosed() { + return this.__left === null; } - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - result2 = parse_atom(); - if (result2 !== null) { - result1 = []; - while (result2 !== null) { - result1.push(result2); - result2 = parse_atom(); + + /** + * returns resolved {Reference} + * @method Scope#resolve + * @param {Espree.Identifier} ident - identifier to be resolved. + * @returns {Reference} reference + */ + + }, { + key: "resolve", + value: function resolve(ident) { + var ref = void 0, + i = void 0, + iz = void 0; + + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } } - } else { - result1 = null; - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; + return null; } - if (result0 !== null) { - result0 = (function(offset, subject, as) { - var b = as.length === 1 ? as[0] : { type: 'compound', selectors: as }; - if(subject) b.subject = true; - return b; - })(pos0, result0[0], result0[1]); + + /** + * returns this scope is static + * @method Scope#isStatic + * @returns {boolean} static + */ + + }, { + key: "isStatic", + value: function isStatic() { + return !this.dynamic; } - if (result0 === null) { - pos = pos0; + + /** + * returns this scope has materialized arguments + * @method Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + + }, { + key: "isArgumentsMaterialized", + value: function isArgumentsMaterialized() { + // eslint-disable-line class-methods-use-this + return true; } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_atom() { - var cacheKey = "atom@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + + /** + * returns this scope has materialized `this` reference + * @method Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + + }, { + key: "isThisMaterialized", + value: function isThisMaterialized() { + // eslint-disable-line class-methods-use-this + return true; } - - var result0; - - result0 = parse_wildcard(); - if (result0 === null) { - result0 = parse_identifier(); - if (result0 === null) { - result0 = parse_attr(); - if (result0 === null) { - result0 = parse_field(); - if (result0 === null) { - result0 = parse_negation(); - if (result0 === null) { - result0 = parse_matches(); - if (result0 === null) { - result0 = parse_firstChild(); - if (result0 === null) { - result0 = parse_lastChild(); - if (result0 === null) { - result0 = parse_nthChild(); - if (result0 === null) { - result0 = parse_nthLastChild(); - if (result0 === null) { - result0 = parse_class(); - } - } - } - } - } + }, { + key: "isUsedName", + value: function isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (var i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; } - } } - } + return false; } - - cache[cacheKey] = { - nextPos: pos, - result: result0 + }]); + + return Scope; +}(); + +var GlobalScope = function (_Scope) { + _inherits(GlobalScope, _Scope); + + function GlobalScope(scopeManager, block) { + _classCallCheck(this, GlobalScope); + + var _this = _possibleConstructorReturn(this, (GlobalScope.__proto__ || Object.getPrototypeOf(GlobalScope)).call(this, scopeManager, "global", null, block, false)); + + _this.implicit = { + set: new Map(), + variables: [], + + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] }; - return result0; - } - - function parse_wildcard() { - var cacheKey = "wildcard@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0; - var pos0; - - pos0 = pos; - if (input.charCodeAt(pos) === 42) { - result0 = "*"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result0 !== null) { - result0 = (function(offset, a) { return { type: 'wildcard', value: a }; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_identifier() { - var cacheKey = "identifier@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0, result1; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 35) { - result0 = "#"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"#\""); - } - } - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - result1 = parse_identifierName(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, i) { return { type: 'identifier', value: i }; })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_attr() { - var cacheKey = "attr@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0, result1, result2, result3, result4; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 91) { - result0 = "["; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"[\""); - } - } - if (result0 !== null) { - result1 = parse__(); - if (result1 !== null) { - result2 = parse_attrValue(); - if (result2 !== null) { - result3 = parse__(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 93) { - result4 = "]"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\"]\""); - } - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; + return _this; + } + + _createClass(GlobalScope, [{ + key: "__close", + value: function __close(scopeManager) { + var implicit = []; + + for (var i = 0, iz = this.__left.length; i < iz; ++i) { + var ref = this.__left[i]; + + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, v) { return v; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_attrOps() { - var cacheKey = "attrOps@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0, result1; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - if (/^[><]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[><]"); + }, { + key: "__defineImplicit", + value: function __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, def); } - } - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_attrEqOps() { - var cacheKey = "attrEqOps@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0, result1; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 33) { - result0 = "!"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } } - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); + }]); + + return GlobalScope; +}(Scope); + +var ModuleScope = function (_Scope2) { + _inherits(ModuleScope, _Scope2); + + function ModuleScope(scopeManager, upperScope, block) { + _classCallCheck(this, ModuleScope); + + return _possibleConstructorReturn(this, (ModuleScope.__proto__ || Object.getPrototypeOf(ModuleScope)).call(this, scopeManager, "module", upperScope, block, false)); + } + + return ModuleScope; +}(Scope); + +var FunctionExpressionNameScope = function (_Scope3) { + _inherits(FunctionExpressionNameScope, _Scope3); + + function FunctionExpressionNameScope(scopeManager, upperScope, block) { + _classCallCheck(this, FunctionExpressionNameScope); + + var _this3 = _possibleConstructorReturn(this, (FunctionExpressionNameScope.__proto__ || Object.getPrototypeOf(FunctionExpressionNameScope)).call(this, scopeManager, "function-expression-name", upperScope, block, false)); + + _this3.__define(block.id, new Definition(Variable.FunctionName, block.id, block, null, null, null)); + _this3.functionExpressionScope = true; + return _this3; + } + + return FunctionExpressionNameScope; +}(Scope); + +var CatchScope = function (_Scope4) { + _inherits(CatchScope, _Scope4); + + function CatchScope(scopeManager, upperScope, block) { + _classCallCheck(this, CatchScope); + + return _possibleConstructorReturn(this, (CatchScope.__proto__ || Object.getPrototypeOf(CatchScope)).call(this, scopeManager, "catch", upperScope, block, false)); + } + + return CatchScope; +}(Scope); + +var WithScope = function (_Scope5) { + _inherits(WithScope, _Scope5); + + function WithScope(scopeManager, upperScope, block) { + _classCallCheck(this, WithScope); + + return _possibleConstructorReturn(this, (WithScope.__proto__ || Object.getPrototypeOf(WithScope)).call(this, scopeManager, "with", upperScope, block, false)); + } + + _createClass(WithScope, [{ + key: "__close", + value: function __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return _get(WithScope.prototype.__proto__ || Object.getPrototypeOf(WithScope.prototype), "__close", this).call(this, scopeManager); } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, a) { return a + '='; })(pos0, result0[0]); - } - if (result0 === null) { - pos = pos0; + + for (var i = 0, iz = this.__left.length; i < iz; ++i) { + var ref = this.__left[i]; + + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_attrName() { - var cacheKey = "attrName@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + }]); + + return WithScope; +}(Scope); + +var TDZScope = function (_Scope6) { + _inherits(TDZScope, _Scope6); + + function TDZScope(scopeManager, upperScope, block) { + _classCallCheck(this, TDZScope); + + return _possibleConstructorReturn(this, (TDZScope.__proto__ || Object.getPrototypeOf(TDZScope)).call(this, scopeManager, "TDZ", upperScope, block, false)); + } + + return TDZScope; +}(Scope); + +var BlockScope = function (_Scope7) { + _inherits(BlockScope, _Scope7); + + function BlockScope(scopeManager, upperScope, block) { + _classCallCheck(this, BlockScope); + + return _possibleConstructorReturn(this, (BlockScope.__proto__ || Object.getPrototypeOf(BlockScope)).call(this, scopeManager, "block", upperScope, block, false)); + } + + return BlockScope; +}(Scope); + +var SwitchScope = function (_Scope8) { + _inherits(SwitchScope, _Scope8); + + function SwitchScope(scopeManager, upperScope, block) { + _classCallCheck(this, SwitchScope); + + return _possibleConstructorReturn(this, (SwitchScope.__proto__ || Object.getPrototypeOf(SwitchScope)).call(this, scopeManager, "switch", upperScope, block, false)); + } + + return SwitchScope; +}(Scope); + +var FunctionScope = function (_Scope9) { + _inherits(FunctionScope, _Scope9); + + function FunctionScope(scopeManager, upperScope, block, isMethodDefinition) { + _classCallCheck(this, FunctionScope); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + var _this9 = _possibleConstructorReturn(this, (FunctionScope.__proto__ || Object.getPrototypeOf(FunctionScope)).call(this, scopeManager, "function", upperScope, block, isMethodDefinition)); + + if (_this9.block.type !== Syntax.ArrowFunctionExpression) { + _this9.__defineArguments(); } - - var result0, result1; - var pos0; - - pos0 = pos; - result1 = parse_identifierName(); - if (result1 === null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); + return _this9; + } + + _createClass(FunctionScope, [{ + key: "isArgumentsMaterialized", + value: function isArgumentsMaterialized() { + + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; } - } - } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_identifierName(); - if (result1 === null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } + + if (!this.isStatic()) { + return true; } - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset, i) { return i.join(''); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_attrValue() { - var cacheKey = "attrValue@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; + + var variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; } - - var result0, result1, result2, result3, result4; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - result0 = parse_attrName(); - if (result0 !== null) { - result1 = parse__(); - if (result1 !== null) { - result2 = parse_attrEqOps(); - if (result2 !== null) { - result3 = parse__(); - if (result3 !== null) { - result4 = parse_type(); - if (result4 === null) { - result4 = parse_regex(); - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; + }, { + key: "isThisMaterialized", + value: function isThisMaterialized() { + if (!this.isStatic()) { + return true; } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, name, op, value) { - return { type: 'attribute', name: name, operator: op, value: value }; - })(pos0, result0[0], result0[2], result0[4]); + return this.thisFound; } - if (result0 === null) { - pos = pos0; + }, { + key: "__defineArguments", + value: function __defineArguments() { + this.__defineGeneric("arguments", this.set, this.variables, null, null); + this.taints.set("arguments", true); } - if (result0 === null) { - pos0 = pos; - pos1 = pos; - result0 = parse_attrName(); - if (result0 !== null) { - result1 = parse__(); - if (result1 !== null) { - result2 = parse_attrOps(); - if (result2 !== null) { - result3 = parse__(); - if (result3 !== null) { - result4 = parse_string(); - if (result4 === null) { - result4 = parse_number(); - if (result4 === null) { - result4 = parse_path(); - } - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; + }]); + + return FunctionScope; +}(Scope); + +var ForScope = function (_Scope10) { + _inherits(ForScope, _Scope10); + + function ForScope(scopeManager, upperScope, block) { + _classCallCheck(this, ForScope); + + return _possibleConstructorReturn(this, (ForScope.__proto__ || Object.getPrototypeOf(ForScope)).call(this, scopeManager, "for", upperScope, block, false)); + } + + return ForScope; +}(Scope); + +var ClassScope = function (_Scope11) { + _inherits(ClassScope, _Scope11); + + function ClassScope(scopeManager, upperScope, block) { + _classCallCheck(this, ClassScope); + + return _possibleConstructorReturn(this, (ClassScope.__proto__ || Object.getPrototypeOf(ClassScope)).call(this, scopeManager, "class", upperScope, block, false)); + } + + return ClassScope; +}(Scope); + +module.exports = { + Scope: Scope, + GlobalScope: GlobalScope, + ModuleScope: ModuleScope, + FunctionExpressionNameScope: FunctionExpressionNameScope, + CatchScope: CatchScope, + WithScope: WithScope, + TDZScope: TDZScope, + BlockScope: BlockScope, + SwitchScope: SwitchScope, + FunctionScope: FunctionScope, + ForScope: ForScope, + ClassScope: ClassScope +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"./definition":58,"./reference":61,"./variable":65,"assert":47,"estraverse":71}],65:[function(require,module,exports){ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +"use strict"; + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Variable = function Variable(name, scope) { + _classCallCheck(this, Variable); + + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; +}; + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.TDZ = "TDZ"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +module.exports = Variable; + +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],66:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + { + "raw": "eslint-scope@^3.7.1", + "scope": null, + "escapedName": "eslint-scope", + "name": "eslint-scope", + "rawSpec": "^3.7.1", + "spec": ">=3.7.1 <4.0.0", + "type": "range" + }, + "D:\\users\\r2g\\exps\\eslint-4.5.0" + ] + ], + "_from": "eslint-scope@>=3.7.1 <4.0.0", + "_id": "eslint-scope@3.7.1", + "_inCache": true, + "_location": "/eslint-scope", + "_nodeVersion": "4.3.1", + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/eslint-scope-3.7.1.tgz_1492031610481_0.544424896594137" + }, + "_npmUser": { + "name": "ivolodin", + "email": "ivolodin@gmail.com" + }, + "_npmVersion": "2.14.12", + "_phantomChildren": {}, + "_requested": { + "raw": "eslint-scope@^3.7.1", + "scope": null, + "escapedName": "eslint-scope", + "name": "eslint-scope", + "rawSpec": "^3.7.1", + "spec": ">=3.7.1 <4.0.0", + "type": "range" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.1.tgz", + "_shasum": "3d63c3edfda02e06e01a452ad88caacc7cdcb6e8", + "_shrinkwrap": null, + "_spec": "eslint-scope@^3.7.1", + "_where": "D:\\users\\r2g\\exps\\eslint-4.5.0", + "bugs": { + "url": "https://github.com/eslint/eslint-scope/issues" + }, + "dependencies": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + }, + "description": "ECMAScript scope analyzer for ESLint", + "devDependencies": { + "chai": "^3.4.1", + "eslint": "^3.15.0", + "eslint-config-eslint": "^4.0.0", + "eslint-release": "^0.10.1", + "espree": "^3.1.1", + "istanbul": "^0.4.5", + "mocha": "^3.2.0", + "npm-license": "^0.3.3", + "shelljs": "^0.7.6", + "typescript": "~2.0.10", + "typescript-eslint-parser": "^1.0.0" + }, + "directories": {}, + "dist": { + "shasum": "3d63c3edfda02e06e01a452ad88caacc7cdcb6e8", + "tarball": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.1.tgz" + }, + "engines": { + "node": ">=4.0.0" + }, + "files": [ + "LICENSE", + "README.md", + "lib" + ], + "gitHead": "bec1febf351ae7137a62241c18eb78876ee4fb7f", + "homepage": "http://github.com/eslint/eslint-scope", + "license": "BSD-2-Clause", + "main": "lib/index.js", + "maintainers": [ + { + "name": "eslint", + "email": "nicholas+eslint@nczconsulting.com" + }, + { + "name": "ivolodin", + "email": "ivolodin@gmail.com" + }, + { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + } + ], + "name": "eslint-scope", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/eslint-scope.git" + }, + "scripts": { + "alpharelease": "eslint-prerelease alpha", + "betarelease": "eslint-prerelease beta", + "ci-release": "eslint-ci-release", + "gh-release": "eslint-gh-release", + "lint": "node Makefile.js lint", + "release": "eslint-release", + "test": "node Makefile.js test" + }, + "version": "3.7.1" +} + +},{}],67:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +/* vim: set sw=4 sts=4 : */ +(function () { + + var estraverse = require('estraverse'); + var parser = require('./parser'); + + var isArray = Array.isArray || function isArray(array) { + return {}.toString.call(array) === '[object Array]'; + }; + + var LEFT_SIDE = {}; + var RIGHT_SIDE = {}; + + function esqueryModule() { + + /** + * Get the value of a property which may be multiple levels down in the object. + */ + function getPath(obj, key) { + var i, + keys = key.split("."); + for (i = 0; i < keys.length; i++) { + if (obj == null) { + return obj; } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, name, op, value) { - return { type: 'attribute', name: name, operator: op, value: value }; - })(pos0, result0[0], result0[2], result0[4]); - } - if (result0 === null) { - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - result0 = parse_attrName(); - if (result0 !== null) { - result0 = (function(offset, name) { return { type: 'attribute', name: name }; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; + obj = obj[keys[i]]; } - } - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_string() { - var cacheKey = "string@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0, result1, result2, result3; - var pos0, pos1, pos2, pos3; - - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 34) { - result0 = "\""; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"\\\"\""); - } + return obj; } - if (result0 !== null) { - result1 = []; - if (/^[^\\"]/.test(input.charAt(pos))) { - result2 = input.charAt(pos); - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("[^\\\\\"]"); + + /** + * Determine whether `node` can be reached by following `path`, starting at `ancestor`. + */ + function inPath(node, ancestor, path) { + var field, remainingPath, i; + if (path.length === 0) { + return node === ancestor; } - } - if (result2 === null) { - pos2 = pos; - pos3 = pos; - if (input.charCodeAt(pos) === 92) { - result2 = "\\"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } + if (ancestor == null) { + return false; } - if (result2 !== null) { - if (input.length > pos) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("any character"); + field = ancestor[path[0]]; + remainingPath = path.slice(1); + if (isArray(field)) { + for (i = 0, l = field.length; i < l; ++i) { + if (inPath(node, field[i], remainingPath)) { + return true; + } } - } - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos3; - } + return false; } else { - result2 = null; - pos = pos3; + return inPath(node, field, remainingPath); } - if (result2 !== null) { - result2 = (function(offset, a, b) { return a + b; })(pos2, result2[0], result2[1]); + } + + /** + * Given a `node` and its ancestors, determine if `node` is matched by `selector`. + */ + function matches(node, selector, ancestry) { + var path, ancestor, i, l, p; + if (!selector) { + return true; } - if (result2 === null) { - pos = pos2; + if (!node) { + return false; } - } - while (result2 !== null) { - result1.push(result2); - if (/^[^\\"]/.test(input.charAt(pos))) { - result2 = input.charAt(pos); - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("[^\\\\\"]"); - } + if (!ancestry) { + ancestry = []; } - if (result2 === null) { - pos2 = pos; - pos3 = pos; - if (input.charCodeAt(pos) === 92) { - result2 = "\\"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } - } - if (result2 !== null) { - if (input.length > pos) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("any character"); - } - } - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos3; - } - } else { - result2 = null; - pos = pos3; - } - if (result2 !== null) { - result2 = (function(offset, a, b) { return a + b; })(pos2, result2[0], result2[1]); - } - if (result2 === null) { - pos = pos2; - } + + switch (selector.type) { + case 'wildcard': + return true; + + case 'identifier': + return selector.value.toLowerCase() === node.type.toLowerCase(); + + case 'field': + path = selector.name.split('.'); + ancestor = ancestry[path.length - 1]; + return inPath(node, ancestor, path); + + case 'matches': + for (i = 0, l = selector.selectors.length; i < l; ++i) { + if (matches(node, selector.selectors[i], ancestry)) { + return true; + } + } + return false; + + case 'compound': + for (i = 0, l = selector.selectors.length; i < l; ++i) { + if (!matches(node, selector.selectors[i], ancestry)) { + return false; + } + } + return true; + + case 'not': + for (i = 0, l = selector.selectors.length; i < l; ++i) { + if (matches(node, selector.selectors[i], ancestry)) { + return false; + } + } + return true; + + case 'child': + if (matches(node, selector.right, ancestry)) { + return matches(ancestry[0], selector.left, ancestry.slice(1)); + } + return false; + + case 'descendant': + if (matches(node, selector.right, ancestry)) { + for (i = 0, l = ancestry.length; i < l; ++i) { + if (matches(ancestry[i], selector.left, ancestry.slice(i + 1))) { + return true; + } + } + } + return false; + + case 'attribute': + p = getPath(node, selector.name); + switch (selector.operator) { + case null: + case void 0: + return p != null; + case '=': + switch (selector.value.type) { + case 'regexp': + return selector.value.value.test(p); + case 'literal': + return '' + selector.value.value === '' + p; + case 'type': + return selector.value.value === (typeof p === 'undefined' ? 'undefined' : _typeof(p)); + } + case '!=': + switch (selector.value.type) { + case 'regexp': + return !selector.value.value.test(p); + case 'literal': + return '' + selector.value.value !== '' + p; + case 'type': + return selector.value.value !== (typeof p === 'undefined' ? 'undefined' : _typeof(p)); + } + case '<=': + return p <= selector.value.value; + case '<': + return p < selector.value.value; + case '>': + return p > selector.value.value; + case '>=': + return p >= selector.value.value; + } + + case 'sibling': + return matches(node, selector.right, ancestry) && sibling(node, selector.left, ancestry, LEFT_SIDE) || selector.left.subject && matches(node, selector.left, ancestry) && sibling(node, selector.right, ancestry, RIGHT_SIDE); + + case 'adjacent': + return matches(node, selector.right, ancestry) && adjacent(node, selector.left, ancestry, LEFT_SIDE) || selector.right.subject && matches(node, selector.left, ancestry) && adjacent(node, selector.right, ancestry, RIGHT_SIDE); + + case 'nth-child': + return matches(node, selector.right, ancestry) && nthChild(node, ancestry, function (length) { + return selector.index.value - 1; + }); + + case 'nth-last-child': + return matches(node, selector.right, ancestry) && nthChild(node, ancestry, function (length) { + return length - selector.index.value; + }); + + case 'class': + if (!node.type) return false; + switch (selector.name.toLowerCase()) { + case 'statement': + if (node.type.slice(-9) === 'Statement') return true; + // fallthrough: interface Declaration <: Statement { } + case 'declaration': + return node.type.slice(-11) === 'Declaration'; + case 'pattern': + if (node.type.slice(-7) === 'Pattern') return true; + // fallthrough: interface Expression <: Node, Pattern { } + case 'expression': + return node.type.slice(-10) === 'Expression' || node.type === 'Literal' || node.type === 'Identifier'; + case 'function': + return node.type.slice(0, 8) === 'Function' || node.type === 'ArrowFunctionExpression'; + } + throw new Error('Unknown class name: ' + selector.name); } - } - if (result1 !== null) { - if (input.charCodeAt(pos) === 34) { - result2 = "\""; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"\\\"\""); - } + + throw new Error('Unknown selector type: ' + selector.type); + } + + /* + * Determines if the given node has a sibling that matches the given selector. + */ + function sibling(node, selector, ancestry, side) { + var parent = ancestry[0], + listProp, + startIndex, + keys, + i, + l, + k, + lowerBound, + upperBound; + if (!parent) { + return false; } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; + keys = estraverse.VisitorKeys[parent.type]; + for (i = 0, l = keys.length; i < l; ++i) { + listProp = parent[keys[i]]; + if (isArray(listProp)) { + startIndex = listProp.indexOf(node); + if (startIndex < 0) { + continue; + } + if (side === LEFT_SIDE) { + lowerBound = 0; + upperBound = startIndex; + } else { + lowerBound = startIndex + 1; + upperBound = listProp.length; + } + for (k = lowerBound; k < upperBound; ++k) { + if (matches(listProp[k], selector, ancestry)) { + return true; + } + } + } } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, d) { - return { type: 'literal', value: strUnescape(d.join('')) }; - })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; + return false; } - if (result0 === null) { - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 39) { - result0 = "'"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result0 !== null) { - result1 = []; - if (/^[^\\']/.test(input.charAt(pos))) { - result2 = input.charAt(pos); - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("[^\\\\']"); - } + + /* + * Determines if the given node has an asjacent sibling that matches the given selector. + */ + function adjacent(node, selector, ancestry, side) { + var parent = ancestry[0], + listProp, + keys, + i, + l, + idx; + if (!parent) { + return false; } - if (result2 === null) { - pos2 = pos; - pos3 = pos; - if (input.charCodeAt(pos) === 92) { - result2 = "\\"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } - } - if (result2 !== null) { - if (input.length > pos) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("any character"); - } - } - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos3; + keys = estraverse.VisitorKeys[parent.type]; + for (i = 0, l = keys.length; i < l; ++i) { + listProp = parent[keys[i]]; + if (isArray(listProp)) { + idx = listProp.indexOf(node); + if (idx < 0) { + continue; + } + if (side === LEFT_SIDE && idx > 0 && matches(listProp[idx - 1], selector, ancestry)) { + return true; + } + if (side === RIGHT_SIDE && idx < listProp.length - 1 && matches(listProp[idx + 1], selector, ancestry)) { + return true; + } } - } else { - result2 = null; - pos = pos3; - } - if (result2 !== null) { - result2 = (function(offset, a, b) { return a + b; })(pos2, result2[0], result2[1]); - } - if (result2 === null) { - pos = pos2; - } } - while (result2 !== null) { - result1.push(result2); - if (/^[^\\']/.test(input.charAt(pos))) { - result2 = input.charAt(pos); - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("[^\\\\']"); - } - } - if (result2 === null) { - pos2 = pos; - pos3 = pos; - if (input.charCodeAt(pos) === 92) { - result2 = "\\"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } - } - if (result2 !== null) { - if (input.length > pos) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("any character"); + return false; + } + + /* + * Determines if the given node is the nth child, determined by idxFn, which is given the containing list's length. + */ + function nthChild(node, ancestry, idxFn) { + var parent = ancestry[0], + listProp, + keys, + i, + l, + idx; + if (!parent) { + return false; + } + keys = estraverse.VisitorKeys[parent.type]; + for (i = 0, l = keys.length; i < l; ++i) { + listProp = parent[keys[i]]; + if (isArray(listProp)) { + idx = listProp.indexOf(node); + if (idx >= 0 && idx === idxFn(listProp.length)) { + return true; } - } - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos3; - } - } else { - result2 = null; - pos = pos3; - } - if (result2 !== null) { - result2 = (function(offset, a, b) { return a + b; })(pos2, result2[0], result2[1]); } - if (result2 === null) { - pos = pos2; + } + return false; + } + + /* + * For each selector node marked as a subject, find the portion of the selector that the subject must match. + */ + function subjects(selector, ancestor) { + var results, p; + if (selector == null || (typeof selector === 'undefined' ? 'undefined' : _typeof(selector)) != 'object') { + return []; + } + if (ancestor == null) { + ancestor = selector; + } + results = selector.subject ? [ancestor] : []; + for (p in selector) { + if (!{}.hasOwnProperty.call(selector, p)) { + continue; } - } + [].push.apply(results, subjects(selector[p], p === 'left' ? selector[p] : ancestor)); } - if (result1 !== null) { - if (input.charCodeAt(pos) === 39) { - result2 = "'"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); + return results; + } + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that match the selector. + */ + function match(ast, selector) { + var ancestry = [], + results = [], + altSubjects, + i, + l, + k, + m; + if (!selector) { + return results; + } + altSubjects = subjects(selector); + estraverse.traverse(ast, { + enter: function enter(node, parent) { + if (parent != null) { + ancestry.unshift(parent); + } + if (matches(node, selector, ancestry)) { + if (altSubjects.length) { + for (i = 0, l = altSubjects.length; i < l; ++i) { + if (matches(node, altSubjects[i], ancestry)) { + results.push(node); + } + for (k = 0, m = ancestry.length; k < m; ++k) { + if (matches(ancestry[k], altSubjects[i], ancestry.slice(k + 1))) { + results.push(ancestry[k]); + } + } + } + } else { + results.push(node); + } + } + }, + leave: function leave() { + ancestry.shift(); } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } + }); + return results; + } + + /** + * Parse a selector string and return its AST. + */ + function parse(selector) { + return parser.parse(selector); + } + + /** + * Query the code AST using the selector string. + */ + function query(ast, selector) { + return match(ast, parse(selector)); + } + + query.parse = parse; + query.match = match; + query.matches = matches; + return query.query = query; + } + + if (typeof define === "function" && define.amd) { + define(esqueryModule); + } else if (typeof module !== 'undefined' && module.exports) { + module.exports = esqueryModule(); + } else { + this.esquery = esqueryModule(); + } +})(); + +},{"./parser":68,"estraverse":71}],68:[function(require,module,exports){ +'use strict'; + +var result = function () { + /* + * Generated by PEG.js 0.7.0. + * + * http://pegjs.majda.cz/ + */ + + function quote(s) { + /* + * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a + * string literal except for the closing quote character, backslash, + * carriage return, line separator, paragraph separator, and line feed. + * Any character may appear in the form of an escape sequence. + * + * For portability, we also escape escape all control and non-ASCII + * characters. Note that "\0" and "\v" escape sequences are not used + * because JSHint does not like the first and IE the second. + */ + return '"' + s.replace(/\\/g, '\\\\') // backslash + .replace(/"/g, '\\"') // closing quote character + .replace(/\x08/g, '\\b') // backspace + .replace(/\t/g, '\\t') // horizontal tab + .replace(/\n/g, '\\n') // line feed + .replace(/\f/g, '\\f') // form feed + .replace(/\r/g, '\\r') // carriage return + .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) + '"'; + } + + var result = { + /* + * Parses the input with a generated parser. If the parsing is successfull, + * returns a value explicitly or implicitly specified by the grammar from + * which the parser was generated (see |PEG.buildParser|). If the parsing is + * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. + */ + parse: function parse(input, startRule) { + var parseFunctions = { + "start": parse_start, + "_": parse__, + "identifierName": parse_identifierName, + "binaryOp": parse_binaryOp, + "selectors": parse_selectors, + "selector": parse_selector, + "sequence": parse_sequence, + "atom": parse_atom, + "wildcard": parse_wildcard, + "identifier": parse_identifier, + "attr": parse_attr, + "attrOps": parse_attrOps, + "attrEqOps": parse_attrEqOps, + "attrName": parse_attrName, + "attrValue": parse_attrValue, + "string": parse_string, + "number": parse_number, + "path": parse_path, + "type": parse_type, + "regex": parse_regex, + "field": parse_field, + "negation": parse_negation, + "matches": parse_matches, + "firstChild": parse_firstChild, + "lastChild": parse_lastChild, + "nthChild": parse_nthChild, + "nthLastChild": parse_nthLastChild, + "class": parse_class + }; + + if (startRule !== undefined) { + if (parseFunctions[startRule] === undefined) { + throw new Error("Invalid rule name: " + quote(startRule) + "."); + } + } else { + startRule = "start"; + } + + var pos = 0; + var reportFailures = 0; + var rightmostFailuresPos = 0; + var rightmostFailuresExpected = []; + var cache = {}; + + function padLeft(input, padding, length) { + var result = input; + + var padLength = length - input.length; + for (var i = 0; i < padLength; i++) { + result = padding + result; + } + + return result; + } + + function escape(ch) { + var charCode = ch.charCodeAt(0); + var escapeChar; + var length; + + if (charCode <= 0xFF) { + escapeChar = 'x'; + length = 2; + } else { + escapeChar = 'u'; + length = 4; + } + + return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); + } + + function matchFailed(failure) { + if (pos < rightmostFailuresPos) { + return; + } + + if (pos > rightmostFailuresPos) { + rightmostFailuresPos = pos; + rightmostFailuresExpected = []; + } + + rightmostFailuresExpected.push(failure); + } + + function parse_start() { + var cacheKey = "start@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } + + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse__(); + if (result0 !== null) { + result1 = parse_selectors(); + if (result1 !== null) { + result2 = parse__(); + if (result2 !== null) { + result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; @@ -23255,229 +26236,198 @@ var result = (function(){ result0 = null; pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, ss) { + return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss }; + }(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + result0 = parse__(); if (result0 !== null) { - result0 = (function(offset, d) { - return { type: 'literal', value: strUnescape(d.join('')) }; - })(pos0, result0[1]); + result0 = function (offset) { + return void 0; + }(pos0); } if (result0 === null) { pos = pos0; } } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_number() { - var cacheKey = "number@" + pos; + + function parse__() { + var cacheKey = "_@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - - var result0, result1, result2; - var pos0, pos1, pos2; - - pos0 = pos; - pos1 = pos; - pos2 = pos; + + var result0, result1; + result0 = []; - if (/^[0-9]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); + if (input.charCodeAt(pos) === 32) { + result1 = " "; pos++; } else { result1 = null; if (reportFailures === 0) { - matchFailed("[0-9]"); + matchFailed("\" \""); } } while (result1 !== null) { result0.push(result1); - if (/^[0-9]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); + if (input.charCodeAt(pos) === 32) { + result1 = " "; pos++; } else { result1 = null; if (reportFailures === 0) { - matchFailed("[0-9]"); + matchFailed("\" \""); } } } - if (result0 !== null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos2; - } - } else { - result0 = null; - pos = pos2; + + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } + + function parse_identifierName() { + var cacheKey = "identifierName@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - if (/^[0-9]/.test(input.charAt(pos))) { - result2 = input.charAt(pos); - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("[0-9]"); - } + + var result0, result1; + var pos0; + + pos0 = pos; + if (/^[^ [\],():#!=><~+.]/.test(input.charAt(pos))) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("[^ [\\],():#!=><~+.]"); } - if (result2 !== null) { - result1 = []; - while (result2 !== null) { - result1.push(result2); - if (/^[0-9]/.test(input.charAt(pos))) { - result2 = input.charAt(pos); - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("[0-9]"); - } + } + if (result1 !== null) { + result0 = []; + while (result1 !== null) { + result0.push(result1); + if (/^[^ [\],():#!=><~+.]/.test(input.charAt(pos))) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("[^ [\\],():#!=><~+.]"); } } - } else { - result1 = null; - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; } } else { result0 = null; - pos = pos1; } if (result0 !== null) { - result0 = (function(offset, a, b) { - return { type: 'literal', value: parseFloat((a ? a.join('') : '') + b.join('')) }; - })(pos0, result0[0], result0[1]); + result0 = function (offset, i) { + return i.join(''); + }(pos0, result0); } if (result0 === null) { pos = pos0; } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_path() { - var cacheKey = "path@" + pos; + + function parse_binaryOp() { + var cacheKey = "binaryOp@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - - var result0; - var pos0; - + + var result0, result1, result2; + var pos0, pos1; + pos0 = pos; - result0 = parse_identifierName(); + pos1 = pos; + result0 = parse__(); if (result0 !== null) { - result0 = (function(offset, i) { return { type: 'literal', value: i }; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_type() { - var cacheKey = "type@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0, result1, result2, result3, result4; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 5) === "type(") { - result0 = "type("; - pos += 5; + if (input.charCodeAt(pos) === 62) { + result1 = ">"; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\">\""); + } + } + if (result1 !== null) { + result2 = parse__(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } } else { result0 = null; - if (reportFailures === 0) { - matchFailed("\"type(\""); - } + pos = pos1; } if (result0 !== null) { - result1 = parse__(); - if (result1 !== null) { - if (/^[^ )]/.test(input.charAt(pos))) { - result3 = input.charAt(pos); + result0 = function (offset) { + return 'child'; + }(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse__(); + if (result0 !== null) { + if (input.charCodeAt(pos) === 126) { + result1 = "~"; pos++; } else { - result3 = null; + result1 = null; if (reportFailures === 0) { - matchFailed("[^ )]"); - } - } - if (result3 !== null) { - result2 = []; - while (result3 !== null) { - result2.push(result3); - if (/^[^ )]/.test(input.charAt(pos))) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("[^ )]"); - } - } + matchFailed("\"~\""); } - } else { - result2 = null; } - if (result2 !== null) { - result3 = parse__(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 41) { - result4 = ")"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } + if (result1 !== null) { + result2 = parse__(); + if (result2 !== null) { + result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; @@ -23490,190 +26440,184 @@ var result = (function(){ result0 = null; pos = pos1; } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, t) { return { type: 'type', value: t.join('') }; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - - cache[cacheKey] = { - nextPos: pos, - result: result0 - }; - return result0; - } - - function parse_regex() { - var cacheKey = "regex@" + pos; - var cachedResult = cache[cacheKey]; - if (cachedResult) { - pos = cachedResult.nextPos; - return cachedResult.result; - } - - var result0, result1, result2; - var pos0, pos1; - - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 47) { - result0 = "/"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); + if (result0 !== null) { + result0 = function (offset) { + return 'sibling'; + }(pos0); } - } - if (result0 !== null) { - if (/^[^\/]/.test(input.charAt(pos))) { - result2 = input.charAt(pos); - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("[^\\/]"); - } + if (result0 === null) { + pos = pos0; } - if (result2 !== null) { - result1 = []; - while (result2 !== null) { - result1.push(result2); - if (/^[^\/]/.test(input.charAt(pos))) { - result2 = input.charAt(pos); + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse__(); + if (result0 !== null) { + if (input.charCodeAt(pos) === 43) { + result1 = "+"; pos++; } else { - result2 = null; + result1 = null; if (reportFailures === 0) { - matchFailed("[^\\/]"); + matchFailed("\"+\""); } } - } - } else { - result1 = null; - } - if (result1 !== null) { - if (input.charCodeAt(pos) === 47) { - result2 = "/"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); + if (result1 !== null) { + result2 = parse__(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } - } else { - result0 = null; - pos = pos1; + if (result0 !== null) { + result0 = function (offset) { + return 'adjacent'; + }(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 32) { + result0 = " "; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\" \""); + } + } + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset) { + return 'descendant'; + }(pos0); + } + if (result0 === null) { + pos = pos0; + } + } } - } else { - result0 = null; - pos = pos1; } - if (result0 !== null) { - result0 = (function(offset, d) { return { type: 'regexp', value: new RegExp(d.join('')) }; })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_field() { - var cacheKey = "field@" + pos; + + function parse_selectors() { + var cacheKey = "selectors@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - - var result0, result1, result2, result3, result4; + + var result0, result1, result2, result3, result4, result5; var pos0, pos1, pos2; - + pos0 = pos; pos1 = pos; - if (input.charCodeAt(pos) === 46) { - result0 = "."; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } + result0 = parse_selector(); if (result0 !== null) { - result1 = parse_identifierName(); - if (result1 !== null) { - result2 = []; - pos2 = pos; - if (input.charCodeAt(pos) === 46) { - result3 = "."; + result1 = []; + pos2 = pos; + result2 = parse__(); + if (result2 !== null) { + if (input.charCodeAt(pos) === 44) { + result3 = ","; pos++; } else { result3 = null; if (reportFailures === 0) { - matchFailed("\".\""); + matchFailed("\",\""); } } if (result3 !== null) { - result4 = parse_identifierName(); + result4 = parse__(); if (result4 !== null) { - result3 = [result3, result4]; + result5 = parse_selector(); + if (result5 !== null) { + result2 = [result2, result3, result4, result5]; + } else { + result2 = null; + pos = pos2; + } } else { - result3 = null; + result2 = null; pos = pos2; } } else { - result3 = null; + result2 = null; pos = pos2; } - while (result3 !== null) { - result2.push(result3); - pos2 = pos; - if (input.charCodeAt(pos) === 46) { - result3 = "."; + } else { + result2 = null; + pos = pos2; + } + while (result2 !== null) { + result1.push(result2); + pos2 = pos; + result2 = parse__(); + if (result2 !== null) { + if (input.charCodeAt(pos) === 44) { + result3 = ","; pos++; } else { result3 = null; if (reportFailures === 0) { - matchFailed("\".\""); + matchFailed("\",\""); } } if (result3 !== null) { - result4 = parse_identifierName(); + result4 = parse__(); if (result4 !== null) { - result3 = [result3, result4]; + result5 = parse_selector(); + if (result5 !== null) { + result2 = [result2, result3, result4, result5]; + } else { + result2 = null; + pos = pos2; + } } else { - result3 = null; + result2 = null; pos = pos2; } } else { - result3 = null; + result2 = null; pos = pos2; } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; } else { - result0 = null; - pos = pos1; + result2 = null; + pos = pos2; } + } + if (result1 !== null) { + result0 = [result0, result1]; } else { result0 = null; pos = pos1; @@ -23683,73 +26627,72 @@ var result = (function(){ pos = pos1; } if (result0 !== null) { - result0 = (function(offset, i, is) { - return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)}; - })(pos0, result0[1], result0[2]); + result0 = function (offset, s, ss) { + return [s].concat(ss.map(function (s) { + return s[3]; + })); + }(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_negation() { - var cacheKey = "negation@" + pos; + + function parse_selector() { + var cacheKey = "selector@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - - var result0, result1, result2, result3, result4; - var pos0, pos1; - + + var result0, result1, result2, result3; + var pos0, pos1, pos2; + pos0 = pos; pos1 = pos; - if (input.substr(pos, 5) === ":not(") { - result0 = ":not("; - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":not(\""); - } - } + result0 = parse_sequence(); if (result0 !== null) { - result1 = parse__(); - if (result1 !== null) { - result2 = parse_selectors(); + result1 = []; + pos2 = pos; + result2 = parse_binaryOp(); + if (result2 !== null) { + result3 = parse_sequence(); + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos2; + } + } else { + result2 = null; + pos = pos2; + } + while (result2 !== null) { + result1.push(result2); + pos2 = pos; + result2 = parse_binaryOp(); if (result2 !== null) { - result3 = parse__(); + result3 = parse_sequence(); if (result3 !== null) { - if (input.charCodeAt(pos) === 41) { - result4 = ")"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } + result2 = [result2, result3]; } else { - result0 = null; - pos = pos1; + result2 = null; + pos = pos2; } } else { - result0 = null; - pos = pos1; + result2 = null; + pos = pos2; } + } + if (result1 !== null) { + result0 = [result0, result1]; } else { result0 = null; pos = pos1; @@ -23759,71 +26702,59 @@ var result = (function(){ pos = pos1; } if (result0 !== null) { - result0 = (function(offset, ss) { return { type: 'not', selectors: ss }; })(pos0, result0[2]); + result0 = function (offset, a, ops) { + return ops.reduce(function (memo, rhs) { + return { type: rhs[0], left: memo, right: rhs[1] }; + }, a); + }(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_matches() { - var cacheKey = "matches@" + pos; + + function parse_sequence() { + var cacheKey = "sequence@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - - var result0, result1, result2, result3, result4; + + var result0, result1, result2; var pos0, pos1; - + pos0 = pos; pos1 = pos; - if (input.substr(pos, 9) === ":matches(") { - result0 = ":matches("; - pos += 9; + if (input.charCodeAt(pos) === 33) { + result0 = "!"; + pos++; } else { result0 = null; if (reportFailures === 0) { - matchFailed("\":matches(\""); + matchFailed("\"!\""); } } + result0 = result0 !== null ? result0 : ""; if (result0 !== null) { - result1 = parse__(); - if (result1 !== null) { - result2 = parse_selectors(); - if (result2 !== null) { - result3 = parse__(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 41) { - result4 = ")"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; + result2 = parse_atom(); + if (result2 !== null) { + result1 = []; + while (result2 !== null) { + result1.push(result2); + result2 = parse_atom(); } + } else { + result1 = null; + } + if (result1 !== null) { + result0 = [result0, result1]; } else { result0 = null; pos = pos1; @@ -23833,166 +26764,136 @@ var result = (function(){ pos = pos1; } if (result0 !== null) { - result0 = (function(offset, ss) { return { type: 'matches', selectors: ss }; })(pos0, result0[2]); + result0 = function (offset, subject, as) { + var b = as.length === 1 ? as[0] : { type: 'compound', selectors: as }; + if (subject) b.subject = true; + return b; + }(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_firstChild() { - var cacheKey = "firstChild@" + pos; + + function parse_atom() { + var cacheKey = "atom@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - + var result0; - var pos0; - - pos0 = pos; - if (input.substr(pos, 12) === ":first-child") { - result0 = ":first-child"; - pos += 12; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":first-child\""); + + result0 = parse_wildcard(); + if (result0 === null) { + result0 = parse_identifier(); + if (result0 === null) { + result0 = parse_attr(); + if (result0 === null) { + result0 = parse_field(); + if (result0 === null) { + result0 = parse_negation(); + if (result0 === null) { + result0 = parse_matches(); + if (result0 === null) { + result0 = parse_firstChild(); + if (result0 === null) { + result0 = parse_lastChild(); + if (result0 === null) { + result0 = parse_nthChild(); + if (result0 === null) { + result0 = parse_nthLastChild(); + if (result0 === null) { + result0 = parse_class(); + } + } + } + } + } + } + } + } } } - if (result0 !== null) { - result0 = (function(offset) { return nth(1); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_lastChild() { - var cacheKey = "lastChild@" + pos; + + function parse_wildcard() { + var cacheKey = "wildcard@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - + var result0; var pos0; - + pos0 = pos; - if (input.substr(pos, 11) === ":last-child") { - result0 = ":last-child"; - pos += 11; + if (input.charCodeAt(pos) === 42) { + result0 = "*"; + pos++; } else { result0 = null; if (reportFailures === 0) { - matchFailed("\":last-child\""); + matchFailed("\"*\""); } } if (result0 !== null) { - result0 = (function(offset) { return nthLast(1); })(pos0); + result0 = function (offset, a) { + return { type: 'wildcard', value: a }; + }(pos0, result0); } if (result0 === null) { pos = pos0; } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_nthChild() { - var cacheKey = "nthChild@" + pos; + + function parse_identifier() { + var cacheKey = "identifier@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - - var result0, result1, result2, result3, result4; + + var result0, result1; var pos0, pos1; - + pos0 = pos; pos1 = pos; - if (input.substr(pos, 11) === ":nth-child(") { - result0 = ":nth-child("; - pos += 11; + if (input.charCodeAt(pos) === 35) { + result0 = "#"; + pos++; } else { result0 = null; if (reportFailures === 0) { - matchFailed("\":nth-child(\""); + matchFailed("\"#\""); } } + result0 = result0 !== null ? result0 : ""; if (result0 !== null) { - result1 = parse__(); + result1 = parse_identifierName(); if (result1 !== null) { - if (/^[0-9]/.test(input.charAt(pos))) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("[0-9]"); - } - } - if (result3 !== null) { - result2 = []; - while (result3 !== null) { - result2.push(result3); - if (/^[0-9]/.test(input.charAt(pos))) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("[0-9]"); - } - } - } - } else { - result2 = null; - } - if (result2 !== null) { - result3 = parse__(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 41) { - result4 = ")"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } + result0 = [result0, result1]; } else { result0 = null; pos = pos1; @@ -24002,80 +26903,57 @@ var result = (function(){ pos = pos1; } if (result0 !== null) { - result0 = (function(offset, n) { return nth(parseInt(n.join(''), 10)); })(pos0, result0[2]); + result0 = function (offset, i) { + return { type: 'identifier', value: i }; + }(pos0, result0[1]); } if (result0 === null) { pos = pos0; } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_nthLastChild() { - var cacheKey = "nthLastChild@" + pos; + + function parse_attr() { + var cacheKey = "attr@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - + var result0, result1, result2, result3, result4; var pos0, pos1; - + pos0 = pos; pos1 = pos; - if (input.substr(pos, 16) === ":nth-last-child(") { - result0 = ":nth-last-child("; - pos += 16; + if (input.charCodeAt(pos) === 91) { + result0 = "["; + pos++; } else { result0 = null; if (reportFailures === 0) { - matchFailed("\":nth-last-child(\""); + matchFailed("\"[\""); } } if (result0 !== null) { result1 = parse__(); if (result1 !== null) { - if (/^[0-9]/.test(input.charAt(pos))) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("[0-9]"); - } - } - if (result3 !== null) { - result2 = []; - while (result3 !== null) { - result2.push(result3); - if (/^[0-9]/.test(input.charAt(pos))) { - result3 = input.charAt(pos); - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("[0-9]"); - } - } - } - } else { - result2 = null; - } + result2 = parse_attrValue(); if (result2 !== null) { result3 = parse__(); if (result3 !== null) { - if (input.charCodeAt(pos) === 41) { - result4 = ")"; + if (input.charCodeAt(pos) === 93) { + result4 = "]"; pos++; } else { result4 = null; if (reportFailures === 0) { - matchFailed("\")\""); + matchFailed("\"]\""); } } if (result4 !== null) { @@ -24101,93 +26979,52 @@ var result = (function(){ pos = pos1; } if (result0 !== null) { - result0 = (function(offset, n) { return nthLast(parseInt(n.join(''), 10)); })(pos0, result0[2]); + result0 = function (offset, v) { + return v; + }(pos0, result0[2]); } if (result0 === null) { pos = pos0; } - + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - function parse_class() { - var cacheKey = "class@" + pos; + + function parse_attrOps() { + var cacheKey = "attrOps@" + pos; var cachedResult = cache[cacheKey]; if (cachedResult) { pos = cachedResult.nextPos; return cachedResult.result; } - + var result0, result1; var pos0, pos1; - + pos0 = pos; pos1 = pos; - if (input.charCodeAt(pos) === 58) { - result0 = ":"; + if (/^[><]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[><]"); + } + } + } + cache[cacheKey] = { nextPos: pos, - result: result0 + result: result0 }; return result0; } - - - function cleanupExpected(expected) { - expected.sort(); - - var lastExpected = null; - var cleanExpected = []; - for (var i = 0; i < expected.length; i++) { - if (expected[i] !== lastExpected) { - cleanExpected.push(expected[i]); - lastExpected = expected[i]; - } + + function parse_attrEqOps() { + var cacheKey = "attrEqOps@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - return cleanExpected; - } - - function computeErrorPosition() { - /* - * The first idea was to use |String.split| to break the input up to the - * error position along newlines and derive the line and column from - * there. However IE's |split| implementation is so broken that it was - * enough to prevent it. - */ - - var line = 1; - var column = 1; - var seenCR = false; - - for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { - var ch = input.charAt(i); - if (ch === "\n") { - if (!seenCR) { line++; } - column = 1; - seenCR = false; - } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { - line++; - column = 1; - seenCR = true; - } else { - column++; - seenCR = false; + + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 33) { + result0 = "!"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"!\""); } } - - return { line: line, column: column }; - } - - - function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; } - function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; } - function strUnescape(s) { - return s.replace(/\\(.)/g, function(match, ch) { - switch(ch) { - case 'a': return '\a'; - case 'b': return '\b'; - case 'f': return '\f'; - case 'n': return '\n'; - case 'r': return '\r'; - case 't': return '\t'; - case 'v': return '\v'; - default: return ch; + result0 = result0 !== null ? result0 : ""; + if (result0 !== null) { + if (input.charCodeAt(pos) === 61) { + result1 = "="; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"=\""); } - }); - } - - - var result = parseFunctions[startRule](); - - /* - * The parser is now in one of the following three states: - * - * 1. The parser successfully parsed the whole input. - * - * - |result !== null| - * - |pos === input.length| - * - |rightmostFailuresExpected| may or may not contain something - * - * 2. The parser successfully parsed only a part of the input. - * - * - |result !== null| - * - |pos < input.length| - * - |rightmostFailuresExpected| may or may not contain something - * - * 3. The parser did not successfully parse any part of the input. - * - * - |result === null| - * - |pos === 0| - * - |rightmostFailuresExpected| contains at least one failure - * - * All code following this comment (including called functions) must - * handle these states. - */ - if (result === null || pos !== input.length) { - var offset = Math.max(pos, rightmostFailuresPos); - var found = offset < input.length ? input.charAt(offset) : null; - var errorPosition = computeErrorPosition(); - - throw new this.SyntaxError( - cleanupExpected(rightmostFailuresExpected), - found, - offset, - errorPosition.line, - errorPosition.column - ); - } - - return result; - }, - - /* Returns the parser source code. */ - toSource: function() { return this._source; } - }; - - /* Thrown when a parser encounters a syntax error. */ - - result.SyntaxError = function(expected, found, offset, line, column) { - function buildMessage(expected, found) { - var expectedHumanized, foundHumanized; - - switch (expected.length) { - case 0: - expectedHumanized = "end of input"; - break; - case 1: - expectedHumanized = expected[0]; - break; - default: - expectedHumanized = expected.slice(0, expected.length - 1).join(", ") - + " or " - + expected[expected.length - 1]; - } - - foundHumanized = found ? quote(found) : "end of input"; - - return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; - } - - this.name = "SyntaxError"; - this.expected = expected; - this.found = found; - this.message = buildMessage(expected, found); - this.offset = offset; - this.line = line; - this.column = column; - }; - - result.SyntaxError.prototype = Error.prototype; - - return result; -})(); -if (typeof define === "function" && define.amd) { define(function(){ return result; }); } else if (typeof module !== "undefined" && module.exports) { module.exports = result; } else { this.esquery = result; } - -},{}],90:[function(require,module,exports){ -/* - Copyright (C) 2014 Yusuke Suzuki - - 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 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. -*/ -(function () { - 'use strict'; - - var assign, - estraverse, - isArray, - objectKeys; - - assign = require('object-assign'); - estraverse = require('estraverse'); - - isArray = Array.isArray || function isArray(array) { - return Object.prototype.toString.call(array) === '[object Array]'; - }; - - objectKeys = Object.keys || function (o) { - var keys = [], key; - for (key in o) { - keys.push(key); + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - return keys; - }; - - function isNode(node) { - if (node == null) { - return false; + if (result0 !== null) { + result0 = function (offset, a) { + return a + '='; + }(pos0, result0[0]); } - return typeof node === 'object' && typeof node.type === 'string'; - } - - function isProperty(nodeType, key) { - return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; - } - - function Visitor(visitor, options) { - options = options || {}; - - this.__visitor = visitor || this; - this.__childVisitorKeys = options.childVisitorKeys - ? assign({}, estraverse.VisitorKeys, options.childVisitorKeys) - : estraverse.VisitorKeys; - if (options.fallback === 'iteration') { - this.__fallback = objectKeys; - } else if (typeof options.fallback === 'function') { - this.__fallback = options.fallback; + if (result0 === null) { + pos = pos0; } - } - /* Default method for visiting children. - * When you need to call default visiting operation inside custom visiting - * operation, you can use it with `this.visitChildren(node)`. - */ - Visitor.prototype.visitChildren = function (node) { - var type, children, i, iz, j, jz, child; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - if (node == null) { - return; + function parse_attrName() { + var cacheKey = "attrName@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - type = node.type || estraverse.Syntax.Property; + var result0, result1; + var pos0; - children = this.__childVisitorKeys[type]; - if (!children) { - if (this.__fallback) { - children = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + type + '.'); + pos0 = pos; + result1 = parse_identifierName(); + if (result1 === null) { + if (input.charCodeAt(pos) === 46) { + result1 = "."; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\".\""); } + } } - - for (i = 0, iz = children.length; i < iz; ++i) { - child = node[children[i]]; - if (child) { - if (isArray(child)) { - for (j = 0, jz = child.length; j < jz; ++j) { - if (child[j]) { - if (isNode(child[j]) || isProperty(type, children[i])) { - this.visit(child[j]); - } - } - } - } else if (isNode(child)) { - this.visit(child); + if (result1 !== null) { + result0 = []; + while (result1 !== null) { + result0.push(result1); + result1 = parse_identifierName(); + if (result1 === null) { + if (input.charCodeAt(pos) === 46) { + result1 = "."; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\".\""); } + } } + } + } else { + result0 = null; + } + if (result0 !== null) { + result0 = function (offset, i) { + return i.join(''); + }(pos0, result0); + } + if (result0 === null) { + pos = pos0; } - }; - /* Dispatching node. */ - Visitor.prototype.visit = function (node) { - var type; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - if (node == null) { - return; + function parse_attrValue() { + var cacheKey = "attrValue@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - type = node.type || estraverse.Syntax.Property; - if (this.__visitor[type]) { - this.__visitor[type].call(this, node); - return; - } - this.visitChildren(node); - }; - - exports.version = require('./package.json').version; - exports.Visitor = Visitor; - exports.visit = function (node, visitor, options) { - var v = new Visitor(visitor, options); - v.visit(node); - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ - -},{"./package.json":91,"estraverse":92,"object-assign":116}],91:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "esrecurse@^4.1.0", - "scope": null, - "escapedName": "esrecurse", - "name": "esrecurse", - "rawSpec": "^4.1.0", - "spec": ">=4.1.0 <5.0.0", - "type": "range" - }, - "D:\\users\\r2g\\exps\\eslint-3.19.0\\node_modules\\escope" - ] - ], - "_from": "esrecurse@>=4.1.0 <5.0.0", - "_id": "esrecurse@4.2.0", - "_inCache": true, - "_location": "/esrecurse", - "_nodeVersion": "7.10.0", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/esrecurse-4.2.0.tgz_1497923921530_0.31889034481719136" - }, - "_npmUser": { - "name": "constellation", - "email": "utatane.tea@gmail.com" - }, - "_npmVersion": "4.2.0", - "_phantomChildren": {}, - "_requested": { - "raw": "esrecurse@^4.1.0", - "scope": null, - "escapedName": "esrecurse", - "name": "esrecurse", - "rawSpec": "^4.1.0", - "spec": ">=4.1.0 <5.0.0", - "type": "range" - }, - "_requiredBy": [ - "/escope" - ], - "_resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.0.tgz", - "_shasum": "fa9568d98d3823f9a41d91e902dcab9ea6e5b163", - "_shrinkwrap": null, - "_spec": "esrecurse@^4.1.0", - "_where": "D:\\users\\r2g\\exps\\eslint-3.19.0\\node_modules\\escope", - "babel": { - "presets": [ - "es2015" - ] - }, - "bugs": { - "url": "https://github.com/estools/esrecurse/issues" - }, - "dependencies": { - "estraverse": "^4.1.0", - "object-assign": "^4.0.1" - }, - "description": "ECMAScript AST recursive visitor", - "devDependencies": { - "babel-cli": "^6.24.1", - "babel-eslint": "^7.2.3", - "babel-preset-es2015": "^6.24.1", - "babel-register": "^6.24.1", - "chai": "^4.0.2", - "esprima": "^4.0.0", - "gulp": "^3.9.0", - "gulp-bump": "^2.7.0", - "gulp-eslint": "^4.0.0", - "gulp-filter": "^5.0.0", - "gulp-git": "^2.4.1", - "gulp-mocha": "^4.3.1", - "gulp-tag-version": "^1.2.1", - "jsdoc": "^3.3.0-alpha10", - "minimist": "^1.1.0" - }, - "directories": {}, - "dist": { - "shasum": "fa9568d98d3823f9a41d91e902dcab9ea6e5b163", - "tarball": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.0.tgz" - }, - "engines": { - "node": ">=0.10.0" - }, - "gitHead": "dabe93e7bb8a92f52b8284b358cd30e230920c96", - "homepage": "https://github.com/estools/esrecurse", - "license": "BSD-2-Clause", - "main": "esrecurse.js", - "maintainers": [ - { - "name": "constellation", - "email": "utatane.tea@gmail.com" - }, - { - "name": "michaelficarra", - "email": "npm@michael.ficarra.me" - }, - { - "name": "nzakas", - "email": "nicholas@nczconsulting.com" - } - ], - "name": "esrecurse", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/estools/esrecurse.git" - }, - "scripts": { - "lint": "gulp lint", - "test": "gulp travis", - "unit-test": "gulp test" - }, - "version": "4.2.0" -} - -},{}],92:[function(require,module,exports){ -/* - Copyright (C) 2012-2013 Yusuke Suzuki - Copyright (C) 2012 Ariya Hidayat - - 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 BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/*jslint vars:false, bitwise:true*/ -/*jshint indent:4*/ -/*global exports:true*/ -(function clone(exports) { - 'use strict'; - - var Syntax, - isArray, - VisitorOption, - VisitorKeys, - objectCreate, - objectKeys, - BREAK, - SKIP, - REMOVE; - - function ignoreJSHintError() { } - - isArray = Array.isArray; - if (!isArray) { - isArray = function isArray(array) { - return Object.prototype.toString.call(array) === '[object Array]'; - }; - } + var result0, result1, result2, result3, result4; + var pos0, pos1; - function deepCopy(obj) { - var ret = {}, key, val; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - val = obj[key]; - if (typeof val === 'object' && val !== null) { - ret[key] = deepCopy(val); + pos0 = pos; + pos1 = pos; + result0 = parse_attrName(); + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + result2 = parse_attrEqOps(); + if (result2 !== null) { + result3 = parse__(); + if (result3 !== null) { + result4 = parse_type(); + if (result4 === null) { + result4 = parse_regex(); + } + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; } else { - ret[key] = val; + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - return ret; - } - - function shallowCopy(obj) { - var ret = {}, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - ret[key] = obj[key]; + if (result0 !== null) { + result0 = function (offset, name, op, value) { + return { type: 'attribute', name: name, operator: op, value: value }; + }(pos0, result0[0], result0[2], result0[4]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_attrName(); + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + result2 = parse_attrOps(); + if (result2 !== null) { + result3 = parse__(); + if (result3 !== null) { + result4 = parse_string(); + if (result4 === null) { + result4 = parse_number(); + if (result4 === null) { + result4 = parse_path(); + } + } + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, name, op, value) { + return { type: 'attribute', name: name, operator: op, value: value }; + }(pos0, result0[0], result0[2], result0[4]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + result0 = parse_attrName(); + if (result0 !== null) { + result0 = function (offset, name) { + return { type: 'attribute', name: name }; + }(pos0, result0); + } + if (result0 === null) { + pos = pos0; } + } } - return ret; - } - ignoreJSHintError(shallowCopy); - // based on LLVM libc++ upper_bound / lower_bound - // MIT License + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - function upperBound(array, func) { - var diff, len, i, current; + function parse_string() { + var cacheKey = "string@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } - len = array.length; - i = 0; + var result0, result1, result2, result3; + var pos0, pos1, pos2, pos3; - while (len) { - diff = len >>> 1; - current = i + diff; - if (func(array[current])) { - len = diff; + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 34) { + result0 = "\""; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result0 !== null) { + result1 = []; + if (/^[^\\"]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[^\\\\\"]"); + } + } + if (result2 === null) { + pos2 = pos; + pos3 = pos; + if (input.charCodeAt(pos) === 92) { + result2 = "\\"; + pos++; } else { - i = current + 1; - len -= diff + 1; + result2 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } } - } - return i; - } - - function lowerBound(array, func) { - var diff, len, i, current; - - len = array.length; - i = 0; - - while (len) { - diff = len >>> 1; - current = i + diff; - if (func(array[current])) { - i = current + 1; - len -= diff + 1; + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos3; + } } else { - len = diff; + result2 = null; + pos = pos3; + } + if (result2 !== null) { + result2 = function (offset, a, b) { + return a + b; + }(pos2, result2[0], result2[1]); + } + if (result2 === null) { + pos = pos2; + } + } + while (result2 !== null) { + result1.push(result2); + if (/^[^\\"]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[^\\\\\"]"); + } + } + if (result2 === null) { + pos2 = pos; + pos3 = pos; + if (input.charCodeAt(pos) === 92) { + result2 = "\\"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos3; + } + } else { + result2 = null; + pos = pos3; + } + if (result2 !== null) { + result2 = function (offset, a, b) { + return a + b; + }(pos2, result2[0], result2[1]); + } + if (result2 === null) { + pos = pos2; + } + } + } + if (result1 !== null) { + if (input.charCodeAt(pos) === 34) { + result2 = "\""; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - return i; - } - ignoreJSHintError(lowerBound); - - objectCreate = Object.create || (function () { - function F() { } - - return function (o) { - F.prototype = o; - return new F(); - }; - })(); - - objectKeys = Object.keys || function (o) { - var keys = [], key; - for (key in o) { - keys.push(key); + if (result0 !== null) { + result0 = function (offset, d) { + return { type: 'literal', value: strUnescape(d.join('')) }; + }(pos0, result0[1]); } - return keys; - }; - - function extend(to, from) { - var keys = objectKeys(from), key, i, len; - for (i = 0, len = keys.length; i < len; i += 1) { - key = keys[i]; - to[key] = from[key]; + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 39) { + result0 = "'"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"'\""); + } + } + if (result0 !== null) { + result1 = []; + if (/^[^\\']/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[^\\\\']"); + } + } + if (result2 === null) { + pos2 = pos; + pos3 = pos; + if (input.charCodeAt(pos) === 92) { + result2 = "\\"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos3; + } + } else { + result2 = null; + pos = pos3; + } + if (result2 !== null) { + result2 = function (offset, a, b) { + return a + b; + }(pos2, result2[0], result2[1]); + } + if (result2 === null) { + pos = pos2; + } + } + while (result2 !== null) { + result1.push(result2); + if (/^[^\\']/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[^\\\\']"); + } + } + if (result2 === null) { + pos2 = pos; + pos3 = pos; + if (input.charCodeAt(pos) === 92) { + result2 = "\\"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos3; + } + } else { + result2 = null; + pos = pos3; + } + if (result2 !== null) { + result2 = function (offset, a, b) { + return a + b; + }(pos2, result2[0], result2[1]); + } + if (result2 === null) { + pos = pos2; + } + } + } + if (result1 !== null) { + if (input.charCodeAt(pos) === 39) { + result2 = "'"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"'\""); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, d) { + return { type: 'literal', value: strUnescape(d.join('')) }; + }(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } } - return to; - } - - Syntax = { - AssignmentExpression: 'AssignmentExpression', - AssignmentPattern: 'AssignmentPattern', - ArrayExpression: 'ArrayExpression', - ArrayPattern: 'ArrayPattern', - ArrowFunctionExpression: 'ArrowFunctionExpression', - AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. - BlockStatement: 'BlockStatement', - BinaryExpression: 'BinaryExpression', - BreakStatement: 'BreakStatement', - CallExpression: 'CallExpression', - CatchClause: 'CatchClause', - ClassBody: 'ClassBody', - ClassDeclaration: 'ClassDeclaration', - ClassExpression: 'ClassExpression', - ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. - ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. - ConditionalExpression: 'ConditionalExpression', - ContinueStatement: 'ContinueStatement', - DebuggerStatement: 'DebuggerStatement', - DirectiveStatement: 'DirectiveStatement', - DoWhileStatement: 'DoWhileStatement', - EmptyStatement: 'EmptyStatement', - ExportAllDeclaration: 'ExportAllDeclaration', - ExportDefaultDeclaration: 'ExportDefaultDeclaration', - ExportNamedDeclaration: 'ExportNamedDeclaration', - ExportSpecifier: 'ExportSpecifier', - ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', - ForInStatement: 'ForInStatement', - ForOfStatement: 'ForOfStatement', - FunctionDeclaration: 'FunctionDeclaration', - FunctionExpression: 'FunctionExpression', - GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. - Identifier: 'Identifier', - IfStatement: 'IfStatement', - ImportDeclaration: 'ImportDeclaration', - ImportDefaultSpecifier: 'ImportDefaultSpecifier', - ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', - ImportSpecifier: 'ImportSpecifier', - Literal: 'Literal', - LabeledStatement: 'LabeledStatement', - LogicalExpression: 'LogicalExpression', - MemberExpression: 'MemberExpression', - MetaProperty: 'MetaProperty', - MethodDefinition: 'MethodDefinition', - ModuleSpecifier: 'ModuleSpecifier', - NewExpression: 'NewExpression', - ObjectExpression: 'ObjectExpression', - ObjectPattern: 'ObjectPattern', - Program: 'Program', - Property: 'Property', - RestElement: 'RestElement', - ReturnStatement: 'ReturnStatement', - SequenceExpression: 'SequenceExpression', - SpreadElement: 'SpreadElement', - Super: 'Super', - SwitchStatement: 'SwitchStatement', - SwitchCase: 'SwitchCase', - TaggedTemplateExpression: 'TaggedTemplateExpression', - TemplateElement: 'TemplateElement', - TemplateLiteral: 'TemplateLiteral', - ThisExpression: 'ThisExpression', - ThrowStatement: 'ThrowStatement', - TryStatement: 'TryStatement', - UnaryExpression: 'UnaryExpression', - UpdateExpression: 'UpdateExpression', - VariableDeclaration: 'VariableDeclaration', - VariableDeclarator: 'VariableDeclarator', - WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement', - YieldExpression: 'YieldExpression' - }; - - VisitorKeys = { - AssignmentExpression: ['left', 'right'], - AssignmentPattern: ['left', 'right'], - ArrayExpression: ['elements'], - ArrayPattern: ['elements'], - ArrowFunctionExpression: ['params', 'body'], - AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. - BlockStatement: ['body'], - BinaryExpression: ['left', 'right'], - BreakStatement: ['label'], - CallExpression: ['callee', 'arguments'], - CatchClause: ['param', 'body'], - ClassBody: ['body'], - ClassDeclaration: ['id', 'superClass', 'body'], - ClassExpression: ['id', 'superClass', 'body'], - ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. - ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - ConditionalExpression: ['test', 'consequent', 'alternate'], - ContinueStatement: ['label'], - DebuggerStatement: [], - DirectiveStatement: [], - DoWhileStatement: ['body', 'test'], - EmptyStatement: [], - ExportAllDeclaration: ['source'], - ExportDefaultDeclaration: ['declaration'], - ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], - ExportSpecifier: ['exported', 'local'], - ExpressionStatement: ['expression'], - ForStatement: ['init', 'test', 'update', 'body'], - ForInStatement: ['left', 'right', 'body'], - ForOfStatement: ['left', 'right', 'body'], - FunctionDeclaration: ['id', 'params', 'body'], - FunctionExpression: ['id', 'params', 'body'], - GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - Identifier: [], - IfStatement: ['test', 'consequent', 'alternate'], - ImportDeclaration: ['specifiers', 'source'], - ImportDefaultSpecifier: ['local'], - ImportNamespaceSpecifier: ['local'], - ImportSpecifier: ['imported', 'local'], - Literal: [], - LabeledStatement: ['label', 'body'], - LogicalExpression: ['left', 'right'], - MemberExpression: ['object', 'property'], - MetaProperty: ['meta', 'property'], - MethodDefinition: ['key', 'value'], - ModuleSpecifier: [], - NewExpression: ['callee', 'arguments'], - ObjectExpression: ['properties'], - ObjectPattern: ['properties'], - Program: ['body'], - Property: ['key', 'value'], - RestElement: [ 'argument' ], - ReturnStatement: ['argument'], - SequenceExpression: ['expressions'], - SpreadElement: ['argument'], - Super: [], - SwitchStatement: ['discriminant', 'cases'], - SwitchCase: ['test', 'consequent'], - TaggedTemplateExpression: ['tag', 'quasi'], - TemplateElement: [], - TemplateLiteral: ['quasis', 'expressions'], - ThisExpression: [], - ThrowStatement: ['argument'], - TryStatement: ['block', 'handler', 'finalizer'], - UnaryExpression: ['argument'], - UpdateExpression: ['argument'], - VariableDeclaration: ['declarations'], - VariableDeclarator: ['id', 'init'], - WhileStatement: ['test', 'body'], - WithStatement: ['object', 'body'], - YieldExpression: ['argument'] - }; - - // unique id - BREAK = {}; - SKIP = {}; - REMOVE = {}; - VisitorOption = { - Break: BREAK, - Skip: SKIP, - Remove: REMOVE - }; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - function Reference(parent, key) { - this.parent = parent; - this.key = key; - } + function parse_number() { + var cacheKey = "number@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } - Reference.prototype.replace = function replace(node) { - this.parent[this.key] = node; - }; + var result0, result1, result2; + var pos0, pos1, pos2; - Reference.prototype.remove = function remove() { - if (isArray(this.parent)) { - this.parent.splice(this.key, 1); - return true; + pos0 = pos; + pos1 = pos; + pos2 = pos; + result0 = []; + if (/^[0-9]/.test(input.charAt(pos))) { + result1 = input.charAt(pos); + pos++; } else { - this.replace(null); - return false; + result1 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } } - }; - - function Element(node, path, wrap, ref) { - this.node = node; - this.path = path; - this.wrap = wrap; - this.ref = ref; - } - - function Controller() { } - - // API: - // return property path array from root to current node - Controller.prototype.path = function path() { - var i, iz, j, jz, result, element; - - function addToPath(result, path) { - if (isArray(path)) { - for (j = 0, jz = path.length; j < jz; ++j) { - result.push(path[j]); + while (result1 !== null) { + result0.push(result1); + if (/^[0-9]/.test(input.charAt(pos))) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + } + if (result0 !== null) { + if (input.charCodeAt(pos) === 46) { + result1 = "."; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\".\""); + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos2; + } + } else { + result0 = null; + pos = pos2; + } + result0 = result0 !== null ? result0 : ""; + if (result0 !== null) { + if (/^[0-9]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + if (result2 !== null) { + result1 = []; + while (result2 !== null) { + result1.push(result2); + if (/^[0-9]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); } - } else { - result.push(path); + } } + } else { + result1 = null; + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - - // root node - if (!this.__current.path) { - return null; + if (result0 !== null) { + result0 = function (offset, a, b) { + return { type: 'literal', value: parseFloat((a ? a.join('') : '') + b.join('')) }; + }(pos0, result0[0], result0[1]); } - - // first node is sentinel, second node is root element - result = []; - for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { - element = this.__leavelist[i]; - addToPath(result, element.path); + if (result0 === null) { + pos = pos0; } - addToPath(result, this.__current.path); - return result; - }; - - // API: - // return type of current node - Controller.prototype.type = function () { - var node = this.current(); - return node.type || this.__current.wrap; - }; - // API: - // return array of parent elements - Controller.prototype.parents = function parents() { - var i, iz, result; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - // first node is sentinel - result = []; - for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { - result.push(this.__leavelist[i].node); + function parse_path() { + var cacheKey = "path@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - return result; - }; - - // API: - // return current node - Controller.prototype.current = function current() { - return this.__current.node; - }; - - Controller.prototype.__execute = function __execute(callback, element) { - var previous, result; - - result = undefined; + var result0; + var pos0; - previous = this.__current; - this.__current = element; - this.__state = null; - if (callback) { - result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + pos0 = pos; + result0 = parse_identifierName(); + if (result0 !== null) { + result0 = function (offset, i) { + return { type: 'literal', value: i }; + }(pos0, result0); } - this.__current = previous; - - return result; - }; - - // API: - // notify control skip / break - Controller.prototype.notify = function notify(flag) { - this.__state = flag; - }; - - // API: - // skip child nodes of current node - Controller.prototype.skip = function () { - this.notify(SKIP); - }; - - // API: - // break traversals - Controller.prototype['break'] = function () { - this.notify(BREAK); - }; - - // API: - // remove node - Controller.prototype.remove = function () { - this.notify(REMOVE); - }; - - Controller.prototype.__initialize = function(root, visitor) { - this.visitor = visitor; - this.root = root; - this.__worklist = []; - this.__leavelist = []; - this.__current = null; - this.__state = null; - this.__fallback = null; - if (visitor.fallback === 'iteration') { - this.__fallback = objectKeys; - } else if (typeof visitor.fallback === 'function') { - this.__fallback = visitor.fallback; + if (result0 === null) { + pos = pos0; } - this.__keys = VisitorKeys; - if (visitor.keys) { - this.__keys = extend(objectCreate(this.__keys), visitor.keys); - } - }; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - function isNode(node) { - if (node == null) { - return false; + function parse_type() { + var cacheKey = "type@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - return typeof node === 'object' && typeof node.type === 'string'; - } - function isProperty(nodeType, key) { - return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; - } + var result0, result1, result2, result3, result4; + var pos0, pos1; - Controller.prototype.traverse = function traverse(root, visitor) { - var worklist, - leavelist, - element, - node, - nodeType, - ret, - key, - current, - current2, - candidates, - candidate, - sentinel; - - this.__initialize(root, visitor); - - sentinel = {}; - - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; - - // initialize - worklist.push(new Element(root, null, null, null)); - leavelist.push(new Element(null, null, null, null)); - - while (worklist.length) { - element = worklist.pop(); - - if (element === sentinel) { - element = leavelist.pop(); - - ret = this.__execute(visitor.leave, element); - - if (this.__state === BREAK || ret === BREAK) { - return; - } - continue; + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 5) === "type(") { + result0 = "type("; + pos += 5; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"type(\""); + } + } + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + if (/^[^ )]/.test(input.charAt(pos))) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("[^ )]"); + } } - - if (element.node) { - - ret = this.__execute(visitor.enter, element); - - if (this.__state === BREAK || ret === BREAK) { - return; - } - - worklist.push(sentinel); - leavelist.push(element); - - if (this.__state === SKIP || ret === SKIP) { - continue; + if (result3 !== null) { + result2 = []; + while (result3 !== null) { + result2.push(result3); + if (/^[^ )]/.test(input.charAt(pos))) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("[^ )]"); + } } - - node = element.node; - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } + } + } else { + result2 = null; + } + if (result2 !== null) { + result3 = parse__(); + if (result3 !== null) { + if (input.charCodeAt(pos) === 41) { + result4 = ")"; + pos++; + } else { + result4 = null; + if (reportFailures === 0) { + matchFailed("\")\""); + } } - - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } - - if (isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', null); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, null); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, null)); - } + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - }; - - Controller.prototype.replace = function replace(root, visitor) { - var worklist, - leavelist, - node, - nodeType, - target, - element, - current, - current2, - candidates, - candidate, - sentinel, - outer, - key; - - function removeElem(element) { - var i, - key, - nextElem, - parent; - - if (element.ref.remove()) { - // When the reference is an element of an array. - key = element.ref.key; - parent = element.ref.parent; - - // If removed from array, then decrease following items' keys. - i = worklist.length; - while (i--) { - nextElem = worklist[i]; - if (nextElem.ref && nextElem.ref.parent === parent) { - if (nextElem.ref.key < key) { - break; - } - --nextElem.ref.key; - } - } - } + if (result0 !== null) { + result0 = function (offset, t) { + return { type: 'type', value: t.join('') }; + }(pos0, result0[2]); + } + if (result0 === null) { + pos = pos0; } - this.__initialize(root, visitor); - - sentinel = {}; - - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; - - // initialize - outer = { - root: root + cache[cacheKey] = { + nextPos: pos, + result: result0 }; - element = new Element(root, null, null, new Reference(outer, 'root')); - worklist.push(element); - leavelist.push(element); - - while (worklist.length) { - element = worklist.pop(); - - if (element === sentinel) { - element = leavelist.pop(); - - target = this.__execute(visitor.leave, element); + return result0; + } - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - } + function parse_regex() { + var cacheKey = "regex@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - } + var result0, result1, result2; + var pos0, pos1; - if (this.__state === BREAK || target === BREAK) { - return outer.root; + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 47) { + result0 = "/"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"/\""); + } + } + if (result0 !== null) { + if (/^[^\/]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[^\\/]"); + } + } + if (result2 !== null) { + result1 = []; + while (result2 !== null) { + result1.push(result2); + if (/^[^\/]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[^\\/]"); } - continue; + } } - - target = this.__execute(visitor.enter, element); - - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - element.node = target; + } else { + result1 = null; + } + if (result1 !== null) { + if (input.charCodeAt(pos) === 47) { + result2 = "/"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"/\""); + } } - - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - element.node = null; + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, d) { + return { type: 'regexp', value: new RegExp(d.join('')) }; + }(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - // node may be null - node = element.node; - if (!node) { - continue; - } + function parse_field() { + var cacheKey = "field@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } - worklist.push(sentinel); - leavelist.push(element); + var result0, result1, result2, result3, result4; + var pos0, pos1, pos2; - if (this.__state === SKIP || target === SKIP) { - continue; + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 46) { + result0 = "."; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\".\""); + } + } + if (result0 !== null) { + result1 = parse_identifierName(); + if (result1 !== null) { + result2 = []; + pos2 = pos; + if (input.charCodeAt(pos) === 46) { + result3 = "."; + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("\".\""); + } } - - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } + if (result3 !== null) { + result4 = parse_identifierName(); + if (result4 !== null) { + result3 = [result3, result4]; + } else { + result3 = null; + pos = pos2; + } + } else { + result3 = null; + pos = pos2; } - - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; + while (result3 !== null) { + result2.push(result3); + pos2 = pos; + if (input.charCodeAt(pos) === 46) { + result3 = "."; + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("\".\""); } - - if (isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + if (result3 !== null) { + result4 = parse_identifierName(); + if (result4 !== null) { + result3 = [result3, result4]; + } else { + result3 = null; + pos = pos2; } + } else { + result3 = null; + pos = pos2; + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - - return outer.root; - }; - - function traverse(root, visitor) { - var controller = new Controller(); - return controller.traverse(root, visitor); - } - - function replace(root, visitor) { - var controller = new Controller(); - return controller.replace(root, visitor); - } - - function extendCommentRange(comment, tokens) { - var target; - - target = upperBound(tokens, function search(token) { - return token.range[0] > comment.range[0]; - }); - - comment.extendedRange = [comment.range[0], comment.range[1]]; - - if (target !== tokens.length) { - comment.extendedRange[1] = tokens[target].range[0]; + if (result0 !== null) { + result0 = function (offset, i, is) { + return { type: 'field', name: is.reduce(function (memo, p) { + return memo + p[0] + p[1]; + }, i) }; + }(pos0, result0[1], result0[2]); } - - target -= 1; - if (target >= 0) { - comment.extendedRange[0] = tokens[target].range[1]; + if (result0 === null) { + pos = pos0; } - return comment; - } - - function attachComments(tree, providedComments, tokens) { - // At first, we should calculate extended comment ranges. - var comments = [], comment, len, i, cursor; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - if (!tree.range) { - throw new Error('attachComments needs range information'); + function parse_negation() { + var cacheKey = "negation@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - // tokens array is empty, we attach comments to tree as 'leadingComments' - if (!tokens.length) { - if (providedComments.length) { - for (i = 0, len = providedComments.length; i < len; i += 1) { - comment = deepCopy(providedComments[i]); - comment.extendedRange = [0, tree.range[0]]; - comments.push(comment); - } - tree.leadingComments = comments; - } - return tree; - } + var result0, result1, result2, result3, result4; + var pos0, pos1; - for (i = 0, len = providedComments.length; i < len; i += 1) { - comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 5) === ":not(") { + result0 = ":not("; + pos += 5; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":not(\""); + } } - - // This is based on John Freeman's implementation. - cursor = 0; - traverse(tree, { - enter: function (node) { - var comment; - - while (cursor < comments.length) { - comment = comments[cursor]; - if (comment.extendedRange[1] > node.range[0]) { - break; - } - - if (comment.extendedRange[1] === node.range[0]) { - if (!node.leadingComments) { - node.leadingComments = []; - } - node.leadingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } - - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + result2 = parse_selectors(); + if (result2 !== null) { + result3 = parse__(); + if (result3 !== null) { + if (input.charCodeAt(pos) === 41) { + result4 = ")"; + pos++; + } else { + result4 = null; + if (reportFailures === 0) { + matchFailed("\")\""); + } } - - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - }); + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, ss) { + return { type: 'not', selectors: ss }; + }(pos0, result0[2]); + } + if (result0 === null) { + pos = pos0; + } - cursor = 0; - traverse(tree, { - leave: function (node) { - var comment; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - while (cursor < comments.length) { - comment = comments[cursor]; - if (node.range[1] < comment.extendedRange[0]) { - break; - } + function parse_matches() { + var cacheKey = "matches@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } - if (node.range[1] === comment.extendedRange[0]) { - if (!node.trailingComments) { - node.trailingComments = []; - } - node.trailingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } + var result0, result1, result2, result3, result4; + var pos0, pos1; - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 9) === ":matches(") { + result0 = ":matches("; + pos += 9; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":matches(\""); + } + } + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + result2 = parse_selectors(); + if (result2 !== null) { + result3 = parse__(); + if (result3 !== null) { + if (input.charCodeAt(pos) === 41) { + result4 = ")"; + pos++; + } else { + result4 = null; + if (reportFailures === 0) { + matchFailed("\")\""); + } } - - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; } - }); - - return tree; - } - - exports.version = require('./package.json').version; - exports.Syntax = Syntax; - exports.traverse = traverse; - exports.replace = replace; - exports.attachComments = attachComments; - exports.VisitorKeys = VisitorKeys; - exports.VisitorOption = VisitorOption; - exports.Controller = Controller; - exports.cloneEnvironment = function () { return clone({}); }; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, ss) { + return { type: 'matches', selectors: ss }; + }(pos0, result0[2]); + } + if (result0 === null) { + pos = pos0; + } - return exports; -}(exports)); -/* vim: set sw=4 ts=4 et tw=80 : */ + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } -},{"./package.json":93}],93:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "estraverse@^4.2.0", - "scope": null, - "escapedName": "estraverse", - "name": "estraverse", - "rawSpec": "^4.2.0", - "spec": ">=4.2.0 <5.0.0", - "type": "range" - }, - "D:\\users\\r2g\\exps\\eslint-3.19.0" - ] - ], - "_from": "estraverse@>=4.2.0 <5.0.0", - "_id": "estraverse@4.2.0", - "_inCache": true, - "_location": "/estraverse", - "_nodeVersion": "0.12.9", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/estraverse-4.2.0.tgz_1457646738925_0.7118953282479197" - }, - "_npmUser": { - "name": "nzakas", - "email": "nicholas@nczconsulting.com" - }, - "_npmVersion": "2.14.9", - "_phantomChildren": {}, - "_requested": { - "raw": "estraverse@^4.2.0", - "scope": null, - "escapedName": "estraverse", - "name": "estraverse", - "rawSpec": "^4.2.0", - "spec": ">=4.2.0 <5.0.0", - "type": "range" - }, - "_requiredBy": [ - "/", - "/escope", - "/esquery", - "/esrecurse" - ], - "_resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", - "_shasum": "0dee3fed31fcd469618ce7342099fc1afa0bdb13", - "_shrinkwrap": null, - "_spec": "estraverse@^4.2.0", - "_where": "D:\\users\\r2g\\exps\\eslint-3.19.0", - "bugs": { - "url": "https://github.com/estools/estraverse/issues" - }, - "dependencies": {}, - "description": "ECMAScript JS AST traversal functions", - "devDependencies": { - "babel-preset-es2015": "^6.3.13", - "babel-register": "^6.3.13", - "chai": "^2.1.1", - "espree": "^1.11.0", - "gulp": "^3.8.10", - "gulp-bump": "^0.2.2", - "gulp-filter": "^2.0.0", - "gulp-git": "^1.0.1", - "gulp-tag-version": "^1.2.1", - "jshint": "^2.5.6", - "mocha": "^2.1.0" - }, - "directories": {}, - "dist": { - "shasum": "0dee3fed31fcd469618ce7342099fc1afa0bdb13", - "tarball": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz" - }, - "engines": { - "node": ">=0.10.0" - }, - "gitHead": "6f6a4e99653908e859c7c10d04d9518bf4844ede", - "homepage": "https://github.com/estools/estraverse", - "license": "BSD-2-Clause", - "main": "estraverse.js", - "maintainers": [ - { - "name": "constellation", - "email": "utatane.tea@gmail.com" - }, - { - "name": "michaelficarra", - "email": "npm@michael.ficarra.me" - }, - { - "name": "nzakas", - "email": "nicholas@nczconsulting.com" - } - ], - "name": "estraverse", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/estools/estraverse.git" - }, - "scripts": { - "lint": "jshint estraverse.js", - "test": "npm run-script lint && npm run-script unit-test", - "unit-test": "mocha --compilers js:babel-register" - }, - "version": "4.2.0" -} + function parse_firstChild() { + var cacheKey = "firstChild@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } -},{}],94:[function(require,module,exports){ -/* - Copyright (C) 2013 Yusuke Suzuki + var result0; + var pos0; - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + pos0 = pos; + if (input.substr(pos, 12) === ":first-child") { + result0 = ":first-child"; + pos += 12; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":first-child\""); + } + } + if (result0 !== null) { + result0 = function (offset) { + return nth(1); + }(pos0); + } + if (result0 === null) { + pos = pos0; + } - * 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. + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - 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 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. -*/ + function parse_lastChild() { + var cacheKey = "lastChild@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } -(function () { - 'use strict'; + var result0; + var pos0; - function isExpression(node) { - if (node == null) { return false; } - switch (node.type) { - case 'ArrayExpression': - case 'AssignmentExpression': - case 'BinaryExpression': - case 'CallExpression': - case 'ConditionalExpression': - case 'FunctionExpression': - case 'Identifier': - case 'Literal': - case 'LogicalExpression': - case 'MemberExpression': - case 'NewExpression': - case 'ObjectExpression': - case 'SequenceExpression': - case 'ThisExpression': - case 'UnaryExpression': - case 'UpdateExpression': - return true; + pos0 = pos; + if (input.substr(pos, 11) === ":last-child") { + result0 = ":last-child"; + pos += 11; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":last-child\""); + } } - return false; - } - - function isIterationStatement(node) { - if (node == null) { return false; } - switch (node.type) { - case 'DoWhileStatement': - case 'ForInStatement': - case 'ForStatement': - case 'WhileStatement': - return true; + if (result0 !== null) { + result0 = function (offset) { + return nthLast(1); + }(pos0); } - return false; - } - - function isStatement(node) { - if (node == null) { return false; } - switch (node.type) { - case 'BlockStatement': - case 'BreakStatement': - case 'ContinueStatement': - case 'DebuggerStatement': - case 'DoWhileStatement': - case 'EmptyStatement': - case 'ExpressionStatement': - case 'ForInStatement': - case 'ForStatement': - case 'IfStatement': - case 'LabeledStatement': - case 'ReturnStatement': - case 'SwitchStatement': - case 'ThrowStatement': - case 'TryStatement': - case 'VariableDeclaration': - case 'WhileStatement': - case 'WithStatement': - return true; + if (result0 === null) { + pos = pos0; } - return false; - } - - function isSourceElement(node) { - return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; - } - function trailingStatement(node) { - switch (node.type) { - case 'IfStatement': - if (node.alternate != null) { - return node.alternate; - } - return node.consequent; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - case 'LabeledStatement': - case 'ForStatement': - case 'ForInStatement': - case 'WhileStatement': - case 'WithStatement': - return node.body; + function parse_nthChild() { + var cacheKey = "nthChild@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; } - return null; - } - function isProblematicIfStatement(node) { - var current; + var result0, result1, result2, result3, result4; + var pos0, pos1; - if (node.type !== 'IfStatement') { - return false; - } - if (node.alternate == null) { - return false; + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 11) === ":nth-child(") { + result0 = ":nth-child("; + pos += 11; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":nth-child(\""); + } } - current = node.consequent; - do { - if (current.type === 'IfStatement') { - if (current.alternate == null) { - return true; + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + if (/^[0-9]/.test(input.charAt(pos))) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + if (result3 !== null) { + result2 = []; + while (result3 !== null) { + result2.push(result3); + if (/^[0-9]/.test(input.charAt(pos))) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } } + } + } else { + result2 = null; } - current = trailingStatement(current); - } while (current); + if (result2 !== null) { + result3 = parse__(); + if (result3 !== null) { + if (input.charCodeAt(pos) === 41) { + result4 = ")"; + pos++; + } else { + result4 = null; + if (reportFailures === 0) { + matchFailed("\")\""); + } + } + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, n) { + return nth(parseInt(n.join(''), 10)); + }(pos0, result0[2]); + } + if (result0 === null) { + pos = pos0; + } - return false; - } + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - module.exports = { - isExpression: isExpression, - isStatement: isStatement, - isIterationStatement: isIterationStatement, - isSourceElement: isSourceElement, - isProblematicIfStatement: isProblematicIfStatement, + function parse_nthLastChild() { + var cacheKey = "nthLastChild@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } - trailingStatement: trailingStatement - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ + var result0, result1, result2, result3, result4; + var pos0, pos1; -},{}],95:[function(require,module,exports){ -/* - Copyright (C) 2013-2014 Yusuke Suzuki - Copyright (C) 2014 Ivan Nikulin + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 16) === ":nth-last-child(") { + result0 = ":nth-last-child("; + pos += 16; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":nth-last-child(\""); + } + } + if (result0 !== null) { + result1 = parse__(); + if (result1 !== null) { + if (/^[0-9]/.test(input.charAt(pos))) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + if (result3 !== null) { + result2 = []; + while (result3 !== null) { + result2.push(result3); + if (/^[0-9]/.test(input.charAt(pos))) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + } + } else { + result2 = null; + } + if (result2 !== null) { + result3 = parse__(); + if (result3 !== null) { + if (input.charCodeAt(pos) === 41) { + result4 = ")"; + pos++; + } else { + result4 = null; + if (reportFailures === 0) { + matchFailed("\")\""); + } + } + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, n) { + return nthLast(parseInt(n.join(''), 10)); + }(pos0, result0[2]); + } + if (result0 === null) { + pos = pos0; + } - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - * 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. + function parse_class() { + var cacheKey = "class@" + pos; + var cachedResult = cache[cacheKey]; + if (cachedResult) { + pos = cachedResult.nextPos; + return cachedResult.result; + } - 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 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. -*/ + var result0, result1; + var pos0, pos1; -(function () { - 'use strict'; + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 58) { + result0 = ":"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":\""); + } + } + if (result0 !== null) { + if (input.substr(pos, 9).toLowerCase() === "statement") { + result1 = input.substr(pos, 9); + pos += 9; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"statement\""); + } + } + if (result1 === null) { + if (input.substr(pos, 10).toLowerCase() === "expression") { + result1 = input.substr(pos, 10); + pos += 10; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"expression\""); + } + } + if (result1 === null) { + if (input.substr(pos, 11).toLowerCase() === "declaration") { + result1 = input.substr(pos, 11); + pos += 11; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"declaration\""); + } + } + if (result1 === null) { + if (input.substr(pos, 8).toLowerCase() === "function") { + result1 = input.substr(pos, 8); + pos += 8; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"function\""); + } + } + if (result1 === null) { + if (input.substr(pos, 7).toLowerCase() === "pattern") { + result1 = input.substr(pos, 7); + pos += 7; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"pattern\""); + } + } + } + } + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = function (offset, c) { + return { type: 'class', name: c }; + }(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } - var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; + cache[cacheKey] = { + nextPos: pos, + result: result0 + }; + return result0; + } - // See `tools/generate-identifier-regex.js`. - ES5Regex = { - // ECMAScript 5.1/Unicode v7.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-\u08B2\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\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\u0C59\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\u0D60\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-\u13F4\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\u19C1-\u19C7\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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]/, - // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart: - NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\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-\u08B2\u08E4-\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\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\u0C59\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\u0D60-\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\u1380-\u138F\u13A0-\u13F4\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-\u19D9\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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-\uFE2D\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]/ - }; + function cleanupExpected(expected) { + expected.sort(); - ES6Regex = { - // ECMAScript 6/Unicode v7.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-\u08B2\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\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\u0C59\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\u0D60\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-\u13F4\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\u19C1-\u19C7\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-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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\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]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\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]|\uD87E[\uDC00-\uDE1D]/, - // ECMAScript 6/Unicode v7.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-\u08B2\u08E4-\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\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\u0C59\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\u0D60-\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-\u13F4\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-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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-\uFE2D\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\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]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\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]|\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]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ - }; + var lastExpected = null; + var cleanExpected = []; + for (var i = 0; i < expected.length; i++) { + if (expected[i] !== lastExpected) { + cleanExpected.push(expected[i]); + lastExpected = expected[i]; + } + } + return cleanExpected; + } - function isDecimalDigit(ch) { - return 0x30 <= ch && ch <= 0x39; // 0..9 - } + function computeErrorPosition() { + /* + * The first idea was to use |String.split| to break the input up to the + * error position along newlines and derive the line and column from + * there. However IE's |split| implementation is so broken that it was + * enough to prevent it. + */ - function isHexDigit(ch) { - return 0x30 <= ch && ch <= 0x39 || // 0..9 - 0x61 <= ch && ch <= 0x66 || // a..f - 0x41 <= ch && ch <= 0x46; // A..F - } + var line = 1; + var column = 1; + var seenCR = false; - function isOctalDigit(ch) { - return ch >= 0x30 && ch <= 0x37; // 0..7 - } + for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { + var ch = input.charAt(i); + if (ch === "\n") { + if (!seenCR) { + line++; + } + column = 1; + seenCR = false; + } else if (ch === "\r" || ch === '\u2028' || ch === '\u2029') { + line++; + column = 1; + seenCR = true; + } else { + column++; + seenCR = false; + } + } - // 7.2 White Space + return { line: line, column: column }; + } - NON_ASCII_WHITESPACES = [ - 0x1680, 0x180E, - 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, - 0x202F, 0x205F, - 0x3000, - 0xFEFF - ]; + function nth(n) { + return { type: 'nth-child', index: { type: 'literal', value: n } }; + } + function nthLast(n) { + return { type: 'nth-last-child', index: { type: 'literal', value: n } }; + } + function strUnescape(s) { + return s.replace(/\\(.)/g, function (match, ch) { + switch (ch) { + case 'a': + return '\a'; + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + default: + return ch; + } + }); + } - function isWhiteSpace(ch) { - return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || - ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; - } + var result = parseFunctions[startRule](); - // 7.3 Line Terminators + /* + * The parser is now in one of the following three states: + * + * 1. The parser successfully parsed the whole input. + * + * - |result !== null| + * - |pos === input.length| + * - |rightmostFailuresExpected| may or may not contain something + * + * 2. The parser successfully parsed only a part of the input. + * + * - |result !== null| + * - |pos < input.length| + * - |rightmostFailuresExpected| may or may not contain something + * + * 3. The parser did not successfully parse any part of the input. + * + * - |result === null| + * - |pos === 0| + * - |rightmostFailuresExpected| contains at least one failure + * + * All code following this comment (including called functions) must + * handle these states. + */ + if (result === null || pos !== input.length) { + var offset = Math.max(pos, rightmostFailuresPos); + var found = offset < input.length ? input.charAt(offset) : null; + var errorPosition = computeErrorPosition(); - function isLineTerminator(ch) { - return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; - } + throw new this.SyntaxError(cleanupExpected(rightmostFailuresExpected), found, offset, errorPosition.line, errorPosition.column); + } - // 7.6 Identifier Names and Identifiers + return result; + }, - function fromCodePoint(cp) { - if (cp <= 0xFFFF) { return String.fromCharCode(cp); } - var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); - var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00); - return cu1 + cu2; + /* Returns the parser source code. */ + toSource: function toSource() { + return this._source; } + }; - IDENTIFIER_START = new Array(0x80); - for(ch = 0; ch < 0x80; ++ch) { - IDENTIFIER_START[ch] = - ch >= 0x61 && ch <= 0x7A || // a..z - ch >= 0x41 && ch <= 0x5A || // A..Z - ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) - } + /* Thrown when a parser encounters a syntax error. */ - IDENTIFIER_PART = new Array(0x80); - for(ch = 0; ch < 0x80; ++ch) { - IDENTIFIER_PART[ch] = - ch >= 0x61 && ch <= 0x7A || // a..z - ch >= 0x41 && ch <= 0x5A || // A..Z - ch >= 0x30 && ch <= 0x39 || // 0..9 - ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) - } + result.SyntaxError = function (expected, found, offset, line, column) { + function buildMessage(expected, found) { + var expectedHumanized, foundHumanized; - function isIdentifierStartES5(ch) { - return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); - } + switch (expected.length) { + case 0: + expectedHumanized = "end of input"; + break; + case 1: + expectedHumanized = expected[0]; + break; + default: + expectedHumanized = expected.slice(0, expected.length - 1).join(", ") + " or " + expected[expected.length - 1]; + } - function isIdentifierPartES5(ch) { - return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); - } + foundHumanized = found ? quote(found) : "end of input"; - function isIdentifierStartES6(ch) { - return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; } - function isIdentifierPartES6(ch) { - return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); - } + this.name = "SyntaxError"; + this.expected = expected; + this.found = found; + this.message = buildMessage(expected, found); + this.offset = offset; + this.line = line; + this.column = column; + }; - module.exports = { - isDecimalDigit: isDecimalDigit, - isHexDigit: isHexDigit, - isOctalDigit: isOctalDigit, - isWhiteSpace: isWhiteSpace, - isLineTerminator: isLineTerminator, - isIdentifierStartES5: isIdentifierStartES5, - isIdentifierPartES5: isIdentifierPartES5, - isIdentifierStartES6: isIdentifierStartES6, - isIdentifierPartES6: isIdentifierPartES6 - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ + result.SyntaxError.prototype = Error.prototype; + + return result; +}(); +if (typeof define === "function" && define.amd) { + define(function () { + return result; + }); +} else if (typeof module !== "undefined" && module.exports) { + module.exports = result; +} else { + undefined.esquery = result; +} + +},{}],69:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -},{}],96:[function(require,module,exports){ /* - Copyright (C) 2013 Yusuke Suzuki + Copyright (C) 2014 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -25891,152 +28780,242 @@ module.exports={ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - (function () { 'use strict'; - var code = require('./code'); + var assign, estraverse, isArray, objectKeys; - function isStrictModeReservedWordES6(id) { - switch (id) { - case 'implements': - case 'interface': - case 'package': - case 'private': - case 'protected': - case 'public': - case 'static': - case 'let': - return true; - default: - return false; - } - } + assign = require('object-assign'); + estraverse = require('estraverse'); - function isKeywordES5(id, strict) { - // yield should not be treated as keyword under non-strict mode. - if (!strict && id === 'yield') { - return false; - } - return isKeywordES6(id, strict); - } + isArray = Array.isArray || function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; - function isKeywordES6(id, strict) { - if (strict && isStrictModeReservedWordES6(id)) { - return true; + objectKeys = Object.keys || function (o) { + var keys = [], + key; + for (key in o) { + keys.push(key); } + return keys; + }; - switch (id.length) { - case 2: - return (id === 'if') || (id === 'in') || (id === 'do'); - case 3: - return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); - 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: + function isNode(node) { + if (node == null) { return false; } + return (typeof node === 'undefined' ? 'undefined' : _typeof(node)) === 'object' && typeof node.type === 'string'; } - function isReservedWordES5(id, strict) { - return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + function isProperty(nodeType, key) { + return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; } - function isReservedWordES6(id, strict) { - return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); - } + function Visitor(visitor, options) { + options = options || {}; - function isRestrictedWord(id) { - return id === 'eval' || id === 'arguments'; + this.__visitor = visitor || this; + this.__childVisitorKeys = options.childVisitorKeys ? assign({}, estraverse.VisitorKeys, options.childVisitorKeys) : estraverse.VisitorKeys; + if (options.fallback === 'iteration') { + this.__fallback = objectKeys; + } else if (typeof options.fallback === 'function') { + this.__fallback = options.fallback; + } } - function isIdentifierNameES5(id) { - var i, iz, ch; - - if (id.length === 0) { return false; } + /* Default method for visiting children. + * When you need to call default visiting operation inside custom visiting + * operation, you can use it with `this.visitChildren(node)`. + */ + Visitor.prototype.visitChildren = function (node) { + var type, children, i, iz, j, jz, child; - ch = id.charCodeAt(0); - if (!code.isIdentifierStartES5(ch)) { - return false; + if (node == null) { + return; } - for (i = 1, iz = id.length; i < iz; ++i) { - ch = id.charCodeAt(i); - if (!code.isIdentifierPartES5(ch)) { - return false; + type = node.type || estraverse.Syntax.Property; + + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); } } - return true; - } - function decodeUtf16(lead, trail) { - return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - } + for (i = 0, iz = children.length; i < iz; ++i) { + child = node[children[i]]; + if (child) { + if (isArray(child)) { + for (j = 0, jz = child.length; j < jz; ++j) { + if (child[j]) { + if (isNode(child[j]) || isProperty(type, children[i])) { + this.visit(child[j]); + } + } + } + } else if (isNode(child)) { + this.visit(child); + } + } + } + }; - function isIdentifierNameES6(id) { - var i, iz, ch, lowCh, check; + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; - if (id.length === 0) { return false; } + if (node == null) { + return; + } - check = code.isIdentifierStartES6; - for (i = 0, iz = id.length; i < iz; ++i) { - ch = id.charCodeAt(i); - if (0xD800 <= ch && ch <= 0xDBFF) { - ++i; - if (i >= iz) { return false; } - lowCh = id.charCodeAt(i); - if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { - return false; - } - ch = decodeUtf16(ch, lowCh); - } - if (!check(ch)) { - return false; - } - check = code.isIdentifierPartES6; + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; } - return true; - } + this.visitChildren(node); + }; - function isIdentifierES5(id, strict) { - return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); - } + exports.version = require('./package.json').version; + exports.Visitor = Visitor; + exports.visit = function (node, visitor, options) { + var v = new Visitor(visitor, options); + v.visit(node); + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ - function isIdentifierES6(id, strict) { - return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); +},{"./package.json":70,"estraverse":71,"object-assign":96}],70:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + { + "raw": "esrecurse@^4.1.0", + "scope": null, + "escapedName": "esrecurse", + "name": "esrecurse", + "rawSpec": "^4.1.0", + "spec": ">=4.1.0 <5.0.0", + "type": "range" + }, + "D:\\users\\r2g\\exps\\eslint-4.5.0\\node_modules\\eslint-scope" + ] + ], + "_from": "esrecurse@>=4.1.0 <5.0.0", + "_id": "esrecurse@4.2.0", + "_inCache": true, + "_location": "/esrecurse", + "_nodeVersion": "7.10.0", + "_npmOperationalInternal": { + "host": "s3://npm-registry-packages", + "tmp": "tmp/esrecurse-4.2.0.tgz_1497923921530_0.31889034481719136" + }, + "_npmUser": { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + "_npmVersion": "4.2.0", + "_phantomChildren": {}, + "_requested": { + "raw": "esrecurse@^4.1.0", + "scope": null, + "escapedName": "esrecurse", + "name": "esrecurse", + "rawSpec": "^4.1.0", + "spec": ">=4.1.0 <5.0.0", + "type": "range" + }, + "_requiredBy": [ + "/eslint-scope" + ], + "_resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.0.tgz", + "_shasum": "fa9568d98d3823f9a41d91e902dcab9ea6e5b163", + "_shrinkwrap": null, + "_spec": "esrecurse@^4.1.0", + "_where": "D:\\users\\r2g\\exps\\eslint-4.5.0\\node_modules\\eslint-scope", + "babel": { + "presets": [ + "es2015" + ] + }, + "bugs": { + "url": "https://github.com/estools/esrecurse/issues" + }, + "dependencies": { + "estraverse": "^4.1.0", + "object-assign": "^4.0.1" + }, + "description": "ECMAScript AST recursive visitor", + "devDependencies": { + "babel-cli": "^6.24.1", + "babel-eslint": "^7.2.3", + "babel-preset-es2015": "^6.24.1", + "babel-register": "^6.24.1", + "chai": "^4.0.2", + "esprima": "^4.0.0", + "gulp": "^3.9.0", + "gulp-bump": "^2.7.0", + "gulp-eslint": "^4.0.0", + "gulp-filter": "^5.0.0", + "gulp-git": "^2.4.1", + "gulp-mocha": "^4.3.1", + "gulp-tag-version": "^1.2.1", + "jsdoc": "^3.3.0-alpha10", + "minimist": "^1.1.0" + }, + "directories": {}, + "dist": { + "shasum": "fa9568d98d3823f9a41d91e902dcab9ea6e5b163", + "tarball": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.0.tgz" + }, + "engines": { + "node": ">=0.10.0" + }, + "gitHead": "dabe93e7bb8a92f52b8284b358cd30e230920c96", + "homepage": "https://github.com/estools/esrecurse", + "license": "BSD-2-Clause", + "main": "esrecurse.js", + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + { + "name": "michaelficarra", + "email": "npm@michael.ficarra.me" + }, + { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" } + ], + "name": "esrecurse", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/estools/esrecurse.git" + }, + "scripts": { + "lint": "gulp lint", + "test": "gulp travis", + "unit-test": "gulp test" + }, + "version": "4.2.0" +} - module.exports = { - isKeywordES5: isKeywordES5, - isKeywordES6: isKeywordES6, - isReservedWordES5: isReservedWordES5, - isReservedWordES6: isReservedWordES6, - isRestrictedWord: isRestrictedWord, - isIdentifierNameES5: isIdentifierNameES5, - isIdentifierNameES6: isIdentifierNameES6, - isIdentifierES5: isIdentifierES5, - isIdentifierES6: isIdentifierES6 - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ +},{}],71:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -},{"./code":95}],97:[function(require,module,exports){ /* - Copyright (C) 2013 Yusuke Suzuki + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -26058,571 +29037,2780 @@ module.exports={ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - - -(function () { +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { 'use strict'; - exports.ast = require('./ast'); - exports.code = require('./code'); - exports.keyword = require('./keyword'); -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ + var Syntax, isArray, VisitorOption, VisitorKeys, objectCreate, objectKeys, BREAK, SKIP, REMOVE; -},{"./ast":94,"./code":95,"./keyword":96}],98:[function(require,module,exports){ -'use strict'; + function ignoreJSHintError() {} -var d = require('d') - , callable = require('es5-ext/object/valid-callable') + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } - , apply = Function.prototype.apply, call = Function.prototype.call - , create = Object.create, defineProperty = Object.defineProperty - , defineProperties = Object.defineProperties - , hasOwnProperty = Object.prototype.hasOwnProperty - , descriptor = { configurable: true, enumerable: false, writable: true } + function deepCopy(obj) { + var ret = {}, + key, + val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } - , on, once, off, emit, methods, descriptors, base; + function shallowCopy(obj) { + var ret = {}, + key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); -on = function (type, listener) { - var data; + // based on LLVM libc++ upper_bound / lower_bound + // MIT License - callable(listener); + function upperBound(array, func) { + var diff, len, i, current; - if (!hasOwnProperty.call(this, '__ee__')) { - data = descriptor.value = create(null); - defineProperty(this, '__ee__', descriptor); - descriptor.value = null; - } else { - data = this.__ee__; - } - if (!data[type]) data[type] = listener; - else if (typeof data[type] === 'object') data[type].push(listener); - else data[type] = [data[type], listener]; + len = array.length; + i = 0; - return this; -}; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } -once = function (type, listener) { - var once, self; + function lowerBound(array, func) { + var diff, len, i, current; - callable(listener); - self = this; - on.call(this, type, once = function () { - off.call(self, type, once); - apply.call(listener, this, arguments); - }); + len = array.length; + i = 0; - once.__eeOnceListener__ = listener; - return this; -}; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); -off = function (type, listener) { - var data, listeners, candidate, i; + objectCreate = Object.create || function () { + function F() {} - callable(listener); + return function (o) { + F.prototype = o; + return new F(); + }; + }(); - if (!hasOwnProperty.call(this, '__ee__')) return this; - data = this.__ee__; - if (!data[type]) return this; - listeners = data[type]; + objectKeys = Object.keys || function (o) { + var keys = [], + key; + for (key in o) { + keys.push(key); + } + return keys; + }; - if (typeof listeners === 'object') { - for (i = 0; (candidate = listeners[i]); ++i) { - if ((candidate === listener) || - (candidate.__eeOnceListener__ === listener)) { - if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; - else listeners.splice(i, 1); - } - } - } else { - if ((listeners === listener) || - (listeners.__eeOnceListener__ === listener)) { - delete data[type]; - } - } + function extend(to, from) { + var keys = objectKeys(from), + key, + i, + len; + for (i = 0, len = keys.length; i < len; i += 1) { + key = keys[i]; + to[key] = from[key]; + } + return to; + } - return this; -}; + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; -emit = function (type) { - var i, l, listener, listeners, args; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: ['argument'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; - if (!hasOwnProperty.call(this, '__ee__')) return; - listeners = this.__ee__[type]; - if (!listeners) return; + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; - if (typeof listeners === 'object') { - l = arguments.length; - args = new Array(l - 1); - for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; - listeners = listeners.slice(); - for (i = 0; (listener = listeners[i]); ++i) { - apply.call(listener, this, args); - } - } else { - switch (arguments.length) { - case 1: - call.call(listeners, this); - break; - case 2: - call.call(listeners, this, arguments[1]); - break; - case 3: - call.call(listeners, this, arguments[1], arguments[2]); - break; - default: - l = arguments.length; - args = new Array(l - 1); - for (i = 1; i < l; ++i) { - args[i - 1] = arguments[i]; - } - apply.call(listeners, this, args); - } - } -}; + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } -methods = { - on: on, - once: once, - off: off, - emit: emit -}; + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; -descriptors = { - on: d(on), - once: d(once), - off: d(off), - emit: d(emit) -}; + Reference.prototype.remove = function remove() { + if (isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; -base = defineProperties({}, descriptors); + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } -module.exports = exports = function (o) { - return (o == null) ? create(base) : defineProperties(Object(o), descriptors); -}; -exports.methods = methods; + function Controller() {} -},{"d":7,"es5-ext/object/valid-callable":49}],99:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; + // root node + if (!this.__current.path) { + return null; + } -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } - if (!this._events) - this._events = {}; + return result; + }; - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; - handler = this._events[type]; + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; - if (isUndefined(handler)) - return false; + result = undefined; - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; - return true; -}; + return result; + }; -EventEmitter.prototype.addListener = function(type, listener) { - var m; + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; - if (!this._events) - this._events = {}; + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; + Controller.prototype.__initialize = function (root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = objectKeys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = extend(objectCreate(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return (typeof node === 'undefined' ? 'undefined' : _typeof(node)) === 'object' && typeof node.type === 'string'; } - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; } - } - return this; -}; + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; -EventEmitter.prototype.on = EventEmitter.prototype.addListener; + this.__initialize(root, visitor); -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + sentinel = {}; - var fired = false; + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - function g() { - this.removeListener(type, g); + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } + while (worklist.length) { + element = worklist.pop(); - g.listener = listener; - this.on(type, g); + if (element === sentinel) { + element = leavelist.pop(); - return this; -}; + ret = this.__execute(visitor.leave, element); -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + if (element.node) { - if (!this._events || !this._events[type]) - return this; + ret = this.__execute(visitor.enter, element); - list = this._events[type]; - length = list.length; - position = -1; + if (this.__state === BREAK || ret === BREAK) { + return; + } - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); + worklist.push(sentinel); + leavelist.push(element); - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } + if (this.__state === SKIP || ret === SKIP) { + continue; + } - if (position < 0) - return this; + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; - return this; -}; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; + function removeElem(element) { + var i, key, nextElem, parent; - if (!this._events) - return this; + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } + this.__initialize(root, visitor); - listeners = this._events[type]; + sentinel = {}; - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - return this; -}; + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; + while (worklist.length) { + element = worklist.pop(); -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; + if (element === sentinel) { + element = leavelist.pop(); - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; + target = this.__execute(visitor.leave, element); -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } -function isFunction(arg) { - return typeof arg === 'function'; -} + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } -function isNumber(arg) { - return typeof arg === 'number'; -} + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} + target = this.__execute(visitor.enter, element); -function isUndefined(arg) { - return arg === void 0; -} + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } -},{}],100:[function(require,module,exports){ -var util = require('util') + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } -var INDENT_START = /[\{\[]/ -var INDENT_END = /[\}\]]/ + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } -module.exports = function() { - var lines = [] - var indent = 0 + // node may be null + node = element.node; + if (!node) { + continue; + } - var push = function(str) { - var spaces = '' - while (spaces.length < indent*2) spaces += ' ' - lines.push(spaces+str) - } + worklist.push(sentinel); + leavelist.push(element); - var line = function(fmt) { - if (!fmt) return line + if (this.__state === SKIP || target === SKIP) { + continue; + } - if (INDENT_END.test(fmt.trim()[0]) && INDENT_START.test(fmt[fmt.length-1])) { - indent-- - push(util.format.apply(util, arguments)) - indent++ - return line - } - if (INDENT_START.test(fmt[fmt.length-1])) { - push(util.format.apply(util, arguments)) - indent++ - return line + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); } - if (INDENT_END.test(fmt.trim()[0])) { - indent-- - push(util.format.apply(util, arguments)) - return line + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); } - push(util.format.apply(util, arguments)) - return line - } + function extendCommentRange(comment, tokens) { + var target; - line.toString = function() { - return lines.join('\n') - } + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); - line.toFunction = function(scope) { - var src = 'return ('+line.toString()+')' + comment.extendedRange = [comment.range[0], comment.range[1]]; - var keys = Object.keys(scope || {}).map(function(key) { - return key - }) + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } - var vals = keys.map(function(key) { - return scope[key] - }) + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } - return Function.apply(null, keys.concat(src)).apply(null, vals) - } + return comment; + } - if (arguments.length) line.apply(null, arguments) + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], + comment, + len, + i, + cursor; - return line -} + if (!tree.range) { + throw new Error('attachComments needs range information'); + } -},{"util":129}],101:[function(require,module,exports){ -var isProperty = require('is-property') + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } -var gen = function(obj, prop) { - return isProperty(prop) ? obj+'.'+prop : obj+'['+JSON.stringify(prop)+']' -} + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } -gen.valid = isProperty -gen.property = function (prop) { - return isProperty(prop) ? prop : JSON.stringify(prop) -} + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function enter(node) { + var comment; -module.exports = gen + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } -},{"is-property":107}],102:[function(require,module,exports){ -module.exports={ - "builtin": { - "Array": false, - "ArrayBuffer": false, - "Boolean": false, - "constructor": false, - "DataView": false, - "Date": false, - "decodeURI": false, - "decodeURIComponent": false, - "encodeURI": false, - "encodeURIComponent": false, - "Error": false, - "escape": false, - "eval": false, - "EvalError": false, - "Float32Array": false, - "Float64Array": false, - "Function": false, - "hasOwnProperty": false, - "Infinity": false, - "Int16Array": false, - "Int32Array": false, - "Int8Array": false, - "isFinite": false, - "isNaN": false, - "isPrototypeOf": false, - "JSON": false, - "Map": false, - "Math": false, - "NaN": false, - "Number": false, - "Object": false, - "parseFloat": false, - "parseInt": false, - "Promise": false, - "propertyIsEnumerable": false, - "Proxy": false, + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function leave(node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = require('./package.json').version; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { + return clone({}); + }; + + return exports; +})(exports); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"./package.json":72}],72:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + { + "raw": "estraverse@^4.2.0", + "scope": null, + "escapedName": "estraverse", + "name": "estraverse", + "rawSpec": "^4.2.0", + "spec": ">=4.2.0 <5.0.0", + "type": "range" + }, + "D:\\users\\r2g\\exps\\eslint-4.5.0" + ] + ], + "_from": "estraverse@>=4.2.0 <5.0.0", + "_id": "estraverse@4.2.0", + "_inCache": true, + "_location": "/estraverse", + "_nodeVersion": "0.12.9", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/estraverse-4.2.0.tgz_1457646738925_0.7118953282479197" + }, + "_npmUser": { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + }, + "_npmVersion": "2.14.9", + "_phantomChildren": {}, + "_requested": { + "raw": "estraverse@^4.2.0", + "scope": null, + "escapedName": "estraverse", + "name": "estraverse", + "rawSpec": "^4.2.0", + "spec": ">=4.2.0 <5.0.0", + "type": "range" + }, + "_requiredBy": [ + "/", + "/eslint-scope", + "/esquery", + "/esrecurse" + ], + "_resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "_shasum": "0dee3fed31fcd469618ce7342099fc1afa0bdb13", + "_shrinkwrap": null, + "_spec": "estraverse@^4.2.0", + "_where": "D:\\users\\r2g\\exps\\eslint-4.5.0", + "bugs": { + "url": "https://github.com/estools/estraverse/issues" + }, + "dependencies": {}, + "description": "ECMAScript JS AST traversal functions", + "devDependencies": { + "babel-preset-es2015": "^6.3.13", + "babel-register": "^6.3.13", + "chai": "^2.1.1", + "espree": "^1.11.0", + "gulp": "^3.8.10", + "gulp-bump": "^0.2.2", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-tag-version": "^1.2.1", + "jshint": "^2.5.6", + "mocha": "^2.1.0" + }, + "directories": {}, + "dist": { + "shasum": "0dee3fed31fcd469618ce7342099fc1afa0bdb13", + "tarball": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz" + }, + "engines": { + "node": ">=0.10.0" + }, + "gitHead": "6f6a4e99653908e859c7c10d04d9518bf4844ede", + "homepage": "https://github.com/estools/estraverse", + "license": "BSD-2-Clause", + "main": "estraverse.js", + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + { + "name": "michaelficarra", + "email": "npm@michael.ficarra.me" + }, + { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + } + ], + "name": "estraverse", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/estools/estraverse.git" + }, + "scripts": { + "lint": "jshint estraverse.js", + "test": "npm run-script lint && npm run-script unit-test", + "unit-test": "mocha --compilers js:babel-register" + }, + "version": "4.2.0" +} + +},{}],73:[function(require,module,exports){ +'use strict'; + +/* + Copyright (C) 2013 Yusuke Suzuki + + 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 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. +*/ + +(function () { + 'use strict'; + + function isExpression(node) { + if (node == null) { + return false; + } + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + return false; + } + + function isIterationStatement(node) { + if (node == null) { + return false; + } + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + return false; + } + + function isStatement(node) { + if (node == null) { + return false; + } + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + if (node.alternate == null) { + return false; + } + current = node.consequent; + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + + trailingStatement: trailingStatement + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],74:[function(require,module,exports){ +'use strict'; + +/* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + 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 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. +*/ + +(function () { + 'use strict'; + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; + + // See `tools/generate-identifier-regex.js`. + ES5Regex = { + // ECMAScript 5.1/Unicode v7.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-\u08B2\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\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\u0C59\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\u0D60\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-\u13F4\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\u19C1-\u19C7\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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]/, + // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\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-\u08B2\u08E4-\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\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\u0C59\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\u0D60-\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\u1380-\u138F\u13A0-\u13F4\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-\u19D9\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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-\uFE2D\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]/ + }; + + ES6Regex = { + // ECMAScript 6/Unicode v7.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-\u08B2\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\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\u0C59\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\u0D60\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-\u13F4\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\u19C1-\u19C7\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-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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\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]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\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]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v7.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-\u08B2\u08E4-\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\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\u0C59\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\u0D60-\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-\u13F4\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-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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-\uFE2D\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\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]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\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]|\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]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } + + // 7.2 White Space + + NON_ASCII_WHITESPACES = [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } + + // 7.6 Identifier Names and Identifiers + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { + return String.fromCharCode(cp); + } + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],75:[function(require,module,exports){ +'use strict'; + +/* + Copyright (C) 2013 Yusuke Suzuki + + 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 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. +*/ + +(function () { + 'use strict'; + + var code = require('./code'); + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return id === 'if' || id === 'in' || id === 'do'; + case 3: + return id === 'var' || id === 'for' || id === 'new' || id === 'try'; + 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; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { + return false; + } + + ch = id.charCodeAt(0); + if (!code.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (!code.isIdentifierPartES5(ch)) { + return false; + } + } + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { + return false; + } + + check = code.isIdentifierStartES6; + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + if (i >= iz) { + return false; + } + lowCh = id.charCodeAt(i); + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + ch = decodeUtf16(ch, lowCh); + } + if (!check(ch)) { + return false; + } + check = code.isIdentifierPartES6; + } + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"./code":74}],76:[function(require,module,exports){ +'use strict'; + +/* + Copyright (C) 2013 Yusuke Suzuki + + 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 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. +*/ + +(function () { + 'use strict'; + + exports.ast = require('./ast'); + exports.code = require('./code'); + exports.keyword = require('./keyword'); +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"./ast":73,"./code":74,"./keyword":75}],77:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function (n) { + if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function (type) { + var er, handler, len, args, i, listeners; + + if (!this._events) this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || isObject(this._events.error) && !this._events.error.length) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) { + listeners[i].apply(this, args); + } + } + + return true; +}; + +EventEmitter.prototype.addListener = function (type, listener) { + var m; + + if (!isFunction(listener)) throw TypeError('listener must be a function'); + + if (!this._events) this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener;else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener);else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function (type, listener) { + if (!isFunction(listener)) throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function (type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || isFunction(list.listener) && list.listener === listener) { + delete this._events[type]; + if (this._events.removeListener) this.emit('removeListener', type, listener); + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || list[i].listener && list[i].listener === listener) { + position = i; + break; + } + } + + if (position < 0) return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function (type) { + var key, listeners; + + if (!this._events) return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) this._events = {};else if (this._events[type]) delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) { + this.removeListener(type, listeners[listeners.length - 1]); + } + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function (type) { + var ret; + if (!this._events || !this._events[type]) ret = [];else if (isFunction(this._events[type])) ret = [this._events[type]];else ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function (type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) return 1;else if (evlistener) return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function (emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],78:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +module.exports = function equal(a, b) { + if (a === b) return true; + + var arrA = Array.isArray(a), + arrB = Array.isArray(b), + i; + + if (arrA && arrB) { + if (a.length != b.length) return false; + for (i = 0; i < a.length; i++) { + if (!equal(a[i], b[i])) return false; + }return true; + } + + if (arrA != arrB) return false; + + if (a && b && (typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object' && (typeof b === 'undefined' ? 'undefined' : _typeof(b)) === 'object') { + var keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) return false; + + var dateA = a instanceof Date, + dateB = b instanceof Date; + if (dateA && dateB) return a.getTime() == b.getTime(); + if (dateA != dateB) return false; + + var regexpA = a instanceof RegExp, + regexpB = b instanceof RegExp; + if (regexpA && regexpB) return a.toString() == b.toString(); + if (regexpA != regexpB) return false; + + for (i = 0; i < keys.length; i++) { + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + }for (i = 0; i < keys.length; i++) { + if (!equal(a[keys[i]], b[keys[i]])) return false; + }return true; + } + + return false; +}; + +},{}],79:[function(require,module,exports){ +"use strict"; + +module.exports = createRBTree; + +var RED = 0; +var BLACK = 1; + +function RBNode(color, key, value, left, right, count) { + this._color = color; + this.key = key; + this.value = value; + this.left = left; + this.right = right; + this._count = count; +} + +function cloneNode(node) { + return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count); +} + +function repaint(color, node) { + return new RBNode(color, node.key, node.value, node.left, node.right, node._count); +} + +function recount(node) { + node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0); +} + +function RedBlackTree(compare, root) { + this._compare = compare; + this.root = root; +} + +var proto = RedBlackTree.prototype; + +Object.defineProperty(proto, "keys", { + get: function get() { + var result = []; + this.forEach(function (k, v) { + result.push(k); + }); + return result; + } +}); + +Object.defineProperty(proto, "values", { + get: function get() { + var result = []; + this.forEach(function (k, v) { + result.push(v); + }); + return result; + } +}); + +//Returns the number of nodes in the tree +Object.defineProperty(proto, "length", { + get: function get() { + if (this.root) { + return this.root._count; + } + return 0; + } +}); + +//Insert a new item into the tree +proto.insert = function (key, value) { + var cmp = this._compare; + //Find point to insert new node at + var n = this.root; + var n_stack = []; + var d_stack = []; + while (n) { + var d = cmp(key, n.key); + n_stack.push(n); + d_stack.push(d); + if (d <= 0) { + n = n.left; + } else { + n = n.right; + } + } + //Rebuild path to leaf node + n_stack.push(new RBNode(RED, key, value, null, null, 1)); + for (var s = n_stack.length - 2; s >= 0; --s) { + var n = n_stack[s]; + if (d_stack[s] <= 0) { + n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s + 1], n.right, n._count + 1); + } else { + n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s + 1], n._count + 1); + } + } + //Rebalance tree using rotations + //console.log("start insert", key, d_stack) + for (var s = n_stack.length - 1; s > 1; --s) { + var p = n_stack[s - 1]; + var n = n_stack[s]; + if (p._color === BLACK || n._color === BLACK) { + break; + } + var pp = n_stack[s - 2]; + if (pp.left === p) { + if (p.left === n) { + var y = pp.right; + if (y && y._color === RED) { + //console.log("LLr") + p._color = BLACK; + pp.right = repaint(BLACK, y); + pp._color = RED; + s -= 1; + } else { + //console.log("LLb") + pp._color = RED; + pp.left = p.right; + p._color = BLACK; + p.right = pp; + n_stack[s - 2] = p; + n_stack[s - 1] = n; + recount(pp); + recount(p); + if (s >= 3) { + var ppp = n_stack[s - 3]; + if (ppp.left === pp) { + ppp.left = p; + } else { + ppp.right = p; + } + } + break; + } + } else { + var y = pp.right; + if (y && y._color === RED) { + //console.log("LRr") + p._color = BLACK; + pp.right = repaint(BLACK, y); + pp._color = RED; + s -= 1; + } else { + //console.log("LRb") + p.right = n.left; + pp._color = RED; + pp.left = n.right; + n._color = BLACK; + n.left = p; + n.right = pp; + n_stack[s - 2] = n; + n_stack[s - 1] = p; + recount(pp); + recount(p); + recount(n); + if (s >= 3) { + var ppp = n_stack[s - 3]; + if (ppp.left === pp) { + ppp.left = n; + } else { + ppp.right = n; + } + } + break; + } + } + } else { + if (p.right === n) { + var y = pp.left; + if (y && y._color === RED) { + //console.log("RRr", y.key) + p._color = BLACK; + pp.left = repaint(BLACK, y); + pp._color = RED; + s -= 1; + } else { + //console.log("RRb") + pp._color = RED; + pp.right = p.left; + p._color = BLACK; + p.left = pp; + n_stack[s - 2] = p; + n_stack[s - 1] = n; + recount(pp); + recount(p); + if (s >= 3) { + var ppp = n_stack[s - 3]; + if (ppp.right === pp) { + ppp.right = p; + } else { + ppp.left = p; + } + } + break; + } + } else { + var y = pp.left; + if (y && y._color === RED) { + //console.log("RLr") + p._color = BLACK; + pp.left = repaint(BLACK, y); + pp._color = RED; + s -= 1; + } else { + //console.log("RLb") + p.left = n.right; + pp._color = RED; + pp.right = n.left; + n._color = BLACK; + n.right = p; + n.left = pp; + n_stack[s - 2] = n; + n_stack[s - 1] = p; + recount(pp); + recount(p); + recount(n); + if (s >= 3) { + var ppp = n_stack[s - 3]; + if (ppp.right === pp) { + ppp.right = n; + } else { + ppp.left = n; + } + } + break; + } + } + } + } + //Return new tree + n_stack[0]._color = BLACK; + return new RedBlackTree(cmp, n_stack[0]); +}; + +//Visit all nodes inorder +function doVisitFull(visit, node) { + if (node.left) { + var v = doVisitFull(visit, node.left); + if (v) { + return v; + } + } + var v = visit(node.key, node.value); + if (v) { + return v; + } + if (node.right) { + return doVisitFull(visit, node.right); + } +} + +//Visit half nodes in order +function doVisitHalf(lo, compare, visit, node) { + var l = compare(lo, node.key); + if (l <= 0) { + if (node.left) { + var v = doVisitHalf(lo, compare, visit, node.left); + if (v) { + return v; + } + } + var v = visit(node.key, node.value); + if (v) { + return v; + } + } + if (node.right) { + return doVisitHalf(lo, compare, visit, node.right); + } +} + +//Visit all nodes within a range +function doVisit(lo, hi, compare, visit, node) { + var l = compare(lo, node.key); + var h = compare(hi, node.key); + var v; + if (l <= 0) { + if (node.left) { + v = doVisit(lo, hi, compare, visit, node.left); + if (v) { + return v; + } + } + if (h > 0) { + v = visit(node.key, node.value); + if (v) { + return v; + } + } + } + if (h > 0 && node.right) { + return doVisit(lo, hi, compare, visit, node.right); + } +} + +proto.forEach = function rbTreeForEach(visit, lo, hi) { + if (!this.root) { + return; + } + switch (arguments.length) { + case 1: + return doVisitFull(visit, this.root); + break; + + case 2: + return doVisitHalf(lo, this._compare, visit, this.root); + break; + + case 3: + if (this._compare(lo, hi) >= 0) { + return; + } + return doVisit(lo, hi, this._compare, visit, this.root); + break; + } +}; + +//First item in list +Object.defineProperty(proto, "begin", { + get: function get() { + var stack = []; + var n = this.root; + while (n) { + stack.push(n); + n = n.left; + } + return new RedBlackTreeIterator(this, stack); + } +}); + +//Last item in list +Object.defineProperty(proto, "end", { + get: function get() { + var stack = []; + var n = this.root; + while (n) { + stack.push(n); + n = n.right; + } + return new RedBlackTreeIterator(this, stack); + } +}); + +//Find the ith item in the tree +proto.at = function (idx) { + if (idx < 0) { + return new RedBlackTreeIterator(this, []); + } + var n = this.root; + var stack = []; + while (true) { + stack.push(n); + if (n.left) { + if (idx < n.left._count) { + n = n.left; + continue; + } + idx -= n.left._count; + } + if (!idx) { + return new RedBlackTreeIterator(this, stack); + } + idx -= 1; + if (n.right) { + if (idx >= n.right._count) { + break; + } + n = n.right; + } else { + break; + } + } + return new RedBlackTreeIterator(this, []); +}; + +proto.ge = function (key) { + var cmp = this._compare; + var n = this.root; + var stack = []; + var last_ptr = 0; + while (n) { + var d = cmp(key, n.key); + stack.push(n); + if (d <= 0) { + last_ptr = stack.length; + } + if (d <= 0) { + n = n.left; + } else { + n = n.right; + } + } + stack.length = last_ptr; + return new RedBlackTreeIterator(this, stack); +}; + +proto.gt = function (key) { + var cmp = this._compare; + var n = this.root; + var stack = []; + var last_ptr = 0; + while (n) { + var d = cmp(key, n.key); + stack.push(n); + if (d < 0) { + last_ptr = stack.length; + } + if (d < 0) { + n = n.left; + } else { + n = n.right; + } + } + stack.length = last_ptr; + return new RedBlackTreeIterator(this, stack); +}; + +proto.lt = function (key) { + var cmp = this._compare; + var n = this.root; + var stack = []; + var last_ptr = 0; + while (n) { + var d = cmp(key, n.key); + stack.push(n); + if (d > 0) { + last_ptr = stack.length; + } + if (d <= 0) { + n = n.left; + } else { + n = n.right; + } + } + stack.length = last_ptr; + return new RedBlackTreeIterator(this, stack); +}; + +proto.le = function (key) { + var cmp = this._compare; + var n = this.root; + var stack = []; + var last_ptr = 0; + while (n) { + var d = cmp(key, n.key); + stack.push(n); + if (d >= 0) { + last_ptr = stack.length; + } + if (d < 0) { + n = n.left; + } else { + n = n.right; + } + } + stack.length = last_ptr; + return new RedBlackTreeIterator(this, stack); +}; + +//Finds the item with key if it exists +proto.find = function (key) { + var cmp = this._compare; + var n = this.root; + var stack = []; + while (n) { + var d = cmp(key, n.key); + stack.push(n); + if (d === 0) { + return new RedBlackTreeIterator(this, stack); + } + if (d <= 0) { + n = n.left; + } else { + n = n.right; + } + } + return new RedBlackTreeIterator(this, []); +}; + +//Removes item with key from tree +proto.remove = function (key) { + var iter = this.find(key); + if (iter) { + return iter.remove(); + } + return this; +}; + +//Returns the item at `key` +proto.get = function (key) { + var cmp = this._compare; + var n = this.root; + while (n) { + var d = cmp(key, n.key); + if (d === 0) { + return n.value; + } + if (d <= 0) { + n = n.left; + } else { + n = n.right; + } + } + return; +}; + +//Iterator for red black tree +function RedBlackTreeIterator(tree, stack) { + this.tree = tree; + this._stack = stack; +} + +var iproto = RedBlackTreeIterator.prototype; + +//Test if iterator is valid +Object.defineProperty(iproto, "valid", { + get: function get() { + return this._stack.length > 0; + } +}); + +//Node of the iterator +Object.defineProperty(iproto, "node", { + get: function get() { + if (this._stack.length > 0) { + return this._stack[this._stack.length - 1]; + } + return null; + }, + enumerable: true +}); + +//Makes a copy of an iterator +iproto.clone = function () { + return new RedBlackTreeIterator(this.tree, this._stack.slice()); +}; + +//Swaps two nodes +function swapNode(n, v) { + n.key = v.key; + n.value = v.value; + n.left = v.left; + n.right = v.right; + n._color = v._color; + n._count = v._count; +} + +//Fix up a double black node in a tree +function fixDoubleBlack(stack) { + var n, p, s, z; + for (var i = stack.length - 1; i >= 0; --i) { + n = stack[i]; + if (i === 0) { + n._color = BLACK; + return; + } + //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) + p = stack[i - 1]; + if (p.left === n) { + //console.log("left child") + s = p.right; + if (s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.right = cloneNode(s); + z = s.right = cloneNode(s.right); + p.right = s.left; + s.left = p; + s.right = z; + s._color = p._color; + n._color = BLACK; + p._color = BLACK; + z._color = BLACK; + recount(p); + recount(s); + if (i > 1) { + var pp = stack[i - 2]; + if (pp.left === p) { + pp.left = s; + } else { + pp.right = s; + } + } + stack[i - 1] = s; + return; + } else if (s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red") + s = p.right = cloneNode(s); + z = s.left = cloneNode(s.left); + p.right = z.left; + s.left = z.right; + z.left = p; + z.right = s; + z._color = p._color; + p._color = BLACK; + s._color = BLACK; + n._color = BLACK; + recount(p); + recount(s); + recount(z); + if (i > 1) { + var pp = stack[i - 2]; + if (pp.left === p) { + pp.left = z; + } else { + pp.right = z; + } + } + stack[i - 1] = z; + return; + } + if (s._color === BLACK) { + if (p._color === RED) { + //console.log("case 2: black sibling, red parent", p.right.value) + p._color = BLACK; + p.right = repaint(RED, s); + return; + } else { + //console.log("case 2: black sibling, black parent", p.right.value) + p.right = repaint(RED, s); + continue; + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s); + p.right = s.left; + s.left = p; + s._color = p._color; + p._color = RED; + recount(p); + recount(s); + if (i > 1) { + var pp = stack[i - 2]; + if (pp.left === p) { + pp.left = s; + } else { + pp.right = s; + } + } + stack[i - 1] = s; + stack[i] = p; + if (i + 1 < stack.length) { + stack[i + 1] = n; + } else { + stack.push(n); + } + i = i + 2; + } + } else { + //console.log("right child") + s = p.left; + if (s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red", p.value, p._color) + s = p.left = cloneNode(s); + z = s.left = cloneNode(s.left); + p.left = s.right; + s.right = p; + s.left = z; + s._color = p._color; + n._color = BLACK; + p._color = BLACK; + z._color = BLACK; + recount(p); + recount(s); + if (i > 1) { + var pp = stack[i - 2]; + if (pp.right === p) { + pp.right = s; + } else { + pp.left = s; + } + } + stack[i - 1] = s; + return; + } else if (s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.left = cloneNode(s); + z = s.right = cloneNode(s.right); + p.left = z.right; + s.right = z.left; + z.right = p; + z.left = s; + z._color = p._color; + p._color = BLACK; + s._color = BLACK; + n._color = BLACK; + recount(p); + recount(s); + recount(z); + if (i > 1) { + var pp = stack[i - 2]; + if (pp.right === p) { + pp.right = z; + } else { + pp.left = z; + } + } + stack[i - 1] = z; + return; + } + if (s._color === BLACK) { + if (p._color === RED) { + //console.log("case 2: black sibling, red parent") + p._color = BLACK; + p.left = repaint(RED, s); + return; + } else { + //console.log("case 2: black sibling, black parent") + p.left = repaint(RED, s); + continue; + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s); + p.left = s.right; + s.right = p; + s._color = p._color; + p._color = RED; + recount(p); + recount(s); + if (i > 1) { + var pp = stack[i - 2]; + if (pp.right === p) { + pp.right = s; + } else { + pp.left = s; + } + } + stack[i - 1] = s; + stack[i] = p; + if (i + 1 < stack.length) { + stack[i + 1] = n; + } else { + stack.push(n); + } + i = i + 2; + } + } + } +} + +//Removes item at iterator from tree +iproto.remove = function () { + var stack = this._stack; + if (stack.length === 0) { + return this.tree; + } + //First copy path to node + var cstack = new Array(stack.length); + var n = stack[stack.length - 1]; + cstack[cstack.length - 1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count); + for (var i = stack.length - 2; i >= 0; --i) { + var n = stack[i]; + if (n.left === stack[i + 1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i + 1], n.right, n._count); + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count); + } + } + + //Get node + n = cstack[cstack.length - 1]; + //console.log("start remove: ", n.value) + + //If not leaf, then swap with previous node + if (n.left && n.right) { + //console.log("moving to leaf") + + //First walk to previous leaf + var split = cstack.length; + n = n.left; + while (n.right) { + cstack.push(n); + n = n.right; + } + //Copy path to leaf + var v = cstack[split - 1]; + cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)); + cstack[split - 1].key = n.key; + cstack[split - 1].value = n.value; + + //Fix up stack + for (var i = cstack.length - 2; i >= split; --i) { + n = cstack[i]; + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count); + } + cstack[split - 1].left = cstack[split]; + } + //console.log("stack=", cstack.map(function(v) { return v.value })) + + //Remove leaf node + n = cstack[cstack.length - 1]; + if (n._color === RED) { + //Easy case: removing red leaf + //console.log("RED leaf") + var p = cstack[cstack.length - 2]; + if (p.left === n) { + p.left = null; + } else if (p.right === n) { + p.right = null; + } + cstack.pop(); + for (var i = 0; i < cstack.length; ++i) { + cstack[i]._count--; + } + return new RedBlackTree(this.tree._compare, cstack[0]); + } else { + if (n.left || n.right) { + //Second easy case: Single child black parent + //console.log("BLACK single child") + if (n.left) { + swapNode(n, n.left); + } else if (n.right) { + swapNode(n, n.right); + } + //Child must be red, so repaint it black to balance color + n._color = BLACK; + for (var i = 0; i < cstack.length - 1; ++i) { + cstack[i]._count--; + } + return new RedBlackTree(this.tree._compare, cstack[0]); + } else if (cstack.length === 1) { + //Third easy case: root + //console.log("ROOT") + return new RedBlackTree(this.tree._compare, null); + } else { + //Hard case: Repaint n, and then do some nasty stuff + //console.log("BLACK leaf no children") + for (var i = 0; i < cstack.length; ++i) { + cstack[i]._count--; + } + var parent = cstack[cstack.length - 2]; + fixDoubleBlack(cstack); + //Fix up links + if (parent.left === n) { + parent.left = null; + } else { + parent.right = null; + } + } + } + return new RedBlackTree(this.tree._compare, cstack[0]); +}; + +//Returns key +Object.defineProperty(iproto, "key", { + get: function get() { + if (this._stack.length > 0) { + return this._stack[this._stack.length - 1].key; + } + return; + }, + enumerable: true +}); + +//Returns value +Object.defineProperty(iproto, "value", { + get: function get() { + if (this._stack.length > 0) { + return this._stack[this._stack.length - 1].value; + } + return; + }, + enumerable: true +}); + +//Returns the position of this iterator in the sorted list +Object.defineProperty(iproto, "index", { + get: function get() { + var idx = 0; + var stack = this._stack; + if (stack.length === 0) { + var r = this.tree.root; + if (r) { + return r._count; + } + return 0; + } else if (stack[stack.length - 1].left) { + idx = stack[stack.length - 1].left._count; + } + for (var s = stack.length - 2; s >= 0; --s) { + if (stack[s + 1] === stack[s].right) { + ++idx; + if (stack[s].left) { + idx += stack[s].left._count; + } + } + } + return idx; + }, + enumerable: true +}); + +//Advances iterator to next element in list +iproto.next = function () { + var stack = this._stack; + if (stack.length === 0) { + return; + } + var n = stack[stack.length - 1]; + if (n.right) { + n = n.right; + while (n) { + stack.push(n); + n = n.left; + } + } else { + stack.pop(); + while (stack.length > 0 && stack[stack.length - 1].right === n) { + n = stack[stack.length - 1]; + stack.pop(); + } + } +}; + +//Checks if iterator is at end of tree +Object.defineProperty(iproto, "hasNext", { + get: function get() { + var stack = this._stack; + if (stack.length === 0) { + return false; + } + if (stack[stack.length - 1].right) { + return true; + } + for (var s = stack.length - 1; s > 0; --s) { + if (stack[s - 1].left === stack[s]) { + return true; + } + } + return false; + } +}); + +//Update value +iproto.update = function (value) { + var stack = this._stack; + if (stack.length === 0) { + throw new Error("Can't update empty node!"); + } + var cstack = new Array(stack.length); + var n = stack[stack.length - 1]; + cstack[cstack.length - 1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count); + for (var i = stack.length - 2; i >= 0; --i) { + n = stack[i]; + if (n.left === stack[i + 1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i + 1], n.right, n._count); + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count); + } + } + return new RedBlackTree(this.tree._compare, cstack[0]); +}; + +//Moves iterator backward one element +iproto.prev = function () { + var stack = this._stack; + if (stack.length === 0) { + return; + } + var n = stack[stack.length - 1]; + if (n.left) { + n = n.left; + while (n) { + stack.push(n); + n = n.right; + } + } else { + stack.pop(); + while (stack.length > 0 && stack[stack.length - 1].left === n) { + n = stack[stack.length - 1]; + stack.pop(); + } + } +}; + +//Checks if iterator is at start of tree +Object.defineProperty(iproto, "hasPrev", { + get: function get() { + var stack = this._stack; + if (stack.length === 0) { + return false; + } + if (stack[stack.length - 1].left) { + return true; + } + for (var s = stack.length - 1; s > 0; --s) { + if (stack[s - 1].right === stack[s]) { + return true; + } + } + return false; + } +}); + +//Default comparison function +function defaultCompare(a, b) { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} + +//Build a tree +function createRBTree(compare) { + return new RedBlackTree(compare || defaultCompare, null); +} + +},{}],80:[function(require,module,exports){ +module.exports={ + "builtin": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, "RangeError": false, "ReferenceError": false, "Reflect": false, @@ -27880,16 +33068,30 @@ module.exports={ } } -},{}],103:[function(require,module,exports){ +},{}],81:[function(require,module,exports){ +'use strict'; + module.exports = require('./globals.json'); -},{"./globals.json":102}],104:[function(require,module,exports){ +},{"./globals.json":80}],82:[function(require,module,exports){ (function (process){ 'use strict'; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); +var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); + } + }return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; + }; +}(); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} module.exports = function () { return new IgnoreBase(); @@ -27970,7 +33172,7 @@ var IgnoreBase = function () { return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0; + && pattern.indexOf('#') !== 0; } }, { key: 'filter', @@ -28311,743 +33513,650 @@ if (process.env.IGNORE_TEST_WIN32 || process.platform === 'win32') { } }).call(this,require('_process')) -},{"_process":123}],105:[function(require,module,exports){ -exports['date-time'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}[tT ]\d{2}:\d{2}:\d{2}(\.\d+)?([zZ]|[+-]\d{2}:\d{2})$/ -exports['date'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$/ -exports['time'] = /^\d{2}:\d{2}:\d{2}$/ -exports['email'] = /^\S+@\S+$/ -exports['ip-address'] = exports['ipv4'] = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/ -exports['ipv6'] = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/ -exports['uri'] = /^[a-zA-Z][a-zA-Z0-9+-.]*:[^\s]*$/ -exports['color'] = /(#?([0-9A-Fa-f]{3,6})\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(yellow)|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\))/ -exports['hostname'] = /^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/ -exports['alpha'] = /^[a-zA-Z]+$/ -exports['alphanumeric'] = /^[a-zA-Z0-9]+$/ -exports['style'] = /\s*(.+?):\s*([^;]+);?/g -exports['phone'] = /^\+(?:[0-9] ?){6,14}[0-9]$/ -exports['utc-millisec'] = /^[0-9]{1,15}\.?[0-9]{0,15}$/ - -},{}],106:[function(require,module,exports){ -var genobj = require('generate-object-property') -var genfun = require('generate-function') -var jsonpointer = require('jsonpointer') -var xtend = require('xtend') -var formats = require('./formats') +},{"_process":104}],83:[function(require,module,exports){ +'use strict'; -var get = function(obj, additionalSchemas, ptr) { +var toString = {}.toString; - var visit = function(sub) { - if (sub && sub.id === ptr) return sub - if (typeof sub !== 'object' || !sub) return null - return Object.keys(sub).reduce(function(res, k) { - return res || visit(sub[k]) - }, null) - } +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; - var res = visit(obj) - if (res) return res +},{}],84:[function(require,module,exports){ +'use strict'; - ptr = ptr.replace(/^#/, '') - ptr = ptr.replace(/\/$/, '') +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - try { - return jsonpointer.get(obj, decodeURI(ptr)) - } catch (err) { - var end = ptr.indexOf('#') - var other - // external reference - if (end !== 0) { - // fragment doesn't exist. - if (end === -1) { - other = additionalSchemas[ptr] - } else { - var ext = ptr.slice(0, end) - other = additionalSchemas[ext] - var fragment = ptr.slice(end).replace(/^#/, '') - try { - return jsonpointer.get(other, fragment) - } catch (err) {} +var traverse = module.exports = function (schema, opts, cb) { + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + _traverse(opts, cb, schema, '', schema); +}; + +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true +}; + +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse.propsKeywords = { + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse.skipKeywords = { + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + +function _traverse(opts, cb, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && (typeof schema === 'undefined' ? 'undefined' : _typeof(schema)) == 'object' && !Array.isArray(schema)) { + cb(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i = 0; i < sch.length; i++) { + _traverse(opts, cb, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i); + } + } + } else if (key in traverse.propsKeywords) { + if (sch && (typeof sch === 'undefined' ? 'undefined' : _typeof(sch)) == 'object') { + for (var prop in sch) { + _traverse(opts, cb, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { + _traverse(opts, cb, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema); } - } else { - other = additionalSchemas[ptr] } - return other || null } } -var formatName = function(field) { - field = JSON.stringify(field) - var pattern = /\[([^\[\]"]+)\]/ - while (pattern.test(field)) field = field.replace(pattern, '."+$1+"') - return field -} - -var types = {} - -types.any = function() { - return 'true' -} - -types.null = function(name) { - return name+' === null' -} - -types.boolean = function(name) { - return 'typeof '+name+' === "boolean"' -} - -types.array = function(name) { - return 'Array.isArray('+name+')' -} - -types.object = function(name) { - return 'typeof '+name+' === "object" && '+name+' && !Array.isArray('+name+')' -} - -types.number = function(name) { - return 'typeof '+name+' === "number"' +function escapeJsonPtr(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); } -types.integer = function(name) { - return 'typeof '+name+' === "number" && (Math.floor('+name+') === '+name+' || '+name+' > 9007199254740992 || '+name+' < -9007199254740992)' -} - -types.string = function(name) { - return 'typeof '+name+' === "string"' -} - -var unique = function(array) { - var list = [] - for (var i = 0; i < array.length; i++) { - list.push(typeof array[i] === 'object' ? JSON.stringify(array[i]) : array[i]) - } - for (var i = 1; i < list.length; i++) { - if (list.indexOf(list[i]) !== i) return false - } - return true -} - -var isMultipleOf = function(name, multipleOf) { - var res; - var factor = ((multipleOf | 0) !== multipleOf) ? Math.pow(10, multipleOf.toString().split('.').pop().length) : 1 - if (factor > 1) { - var factorName = ((name | 0) !== name) ? Math.pow(10, name.toString().split('.').pop().length) : 1 - if (factorName > factor) res = true - else res = Math.round(factor * name) % (factor * multipleOf) - } - else res = name % multipleOf; - return !res; -} - -var compile = function(schema, cache, root, reporter, opts) { - var fmts = opts ? xtend(formats, opts.formats) : formats - var scope = {unique:unique, formats:fmts, isMultipleOf:isMultipleOf} - var verbose = opts ? !!opts.verbose : false; - var greedy = opts && opts.greedy !== undefined ? - opts.greedy : false; +},{}],85:[function(require,module,exports){ +'use strict'; - var syms = {} - var gensym = function(name) { - return name+(syms[name] = (syms[name] || 0)+1) - } +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - var reversePatterns = {} - var patterns = function(p) { - if (reversePatterns[p]) return reversePatterns[p] - var n = gensym('pattern') - scope[n] = new RegExp(p) - reversePatterns[p] = n - return n - } +var json = typeof JSON !== 'undefined' ? JSON : require('jsonify'); - var vars = ['i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'] - var genloop = function() { - var v = vars.shift() - vars.push(v+v[0]) - return v - } +module.exports = function (obj, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var space = opts.space || ''; + if (typeof space === 'number') space = Array(space + 1).join(' '); + var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false; + var replacer = opts.replacer || function (key, value) { + return value; + }; - var visit = function(name, node, reporter, filter) { - var properties = node.properties - var type = node.type - var tuple = false + var cmp = opts.cmp && function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + }(opts.cmp); - if (Array.isArray(node.items)) { // tuple type - properties = {} - node.items.forEach(function(item, i) { - properties[i] = item - }) - type = 'array' - tuple = true - } + var seen = []; + return function stringify(parent, key, node, level) { + var indent = space ? '\n' + new Array(level + 1).join(space) : ''; + var colonSeparator = space ? ': ' : ':'; - var indent = 0 - var error = function(msg, prop, value) { - validate('errors++') - if (reporter === true) { - validate('if (validate.errors === null) validate.errors = []') - if (verbose) { - validate('validate.errors.push({field:%s,message:%s,value:%s,type:%s})', formatName(prop || name), JSON.stringify(msg), value || name, JSON.stringify(type)) - } else { - validate('validate.errors.push({field:%s,message:%s})', formatName(prop || name), JSON.stringify(msg)) + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); } - } - } - if (node.required === true) { - indent++ - validate('if (%s === undefined) {', name) - error('is required') - validate('} else {') - } else { - indent++ - validate('if (%s !== undefined) {', name) - } + node = replacer.call(parent, key, node); - var valid = [].concat(type) - .map(function(t) { - if (t && !types.hasOwnProperty(t)) { - throw new Error('Unknown type: ' + t) + if (node === undefined) { + return; } - - return types[t || 'any'](name) - }) - .join(' || ') || 'true' - - if (valid !== 'true') { - indent++ - validate('if (!(%s)) {', valid) - error('is the wrong type') - validate('} else {') - } - - if (tuple) { - if (node.additionalItems === false) { - validate('if (%s.length > %d) {', name, node.items.length) - error('has additional items') - validate('}') - } else if (node.additionalItems) { - var i = genloop() - validate('for (var %s = %d; %s < %s.length; %s++) {', i, node.items.length, i, name, i) - visit(name+'['+i+']', node.additionalItems, reporter, filter) - validate('}') - } - } - - if (node.format && fmts[node.format]) { - if (type !== 'string' && formats[node.format]) validate('if (%s) {', types.string(name)) - var n = gensym('format') - scope[n] = fmts[node.format] - - if (typeof scope[n] === 'function') validate('if (!%s(%s)) {', n, name) - else validate('if (!%s.test(%s)) {', n, name) - error('must be '+node.format+' format') - validate('}') - if (type !== 'string' && formats[node.format]) validate('}') - } - - if (Array.isArray(node.required)) { - var checkRequired = function (req) { - var prop = genobj(name, req); - validate('if (%s === undefined) {', prop) - error('is required', prop) - validate('missing++') - validate('}') - } - validate('if ((%s)) {', type !== 'object' ? types.object(name) : 'true') - validate('var missing = 0') - node.required.map(checkRequired) - validate('}'); - if (!greedy) { - validate('if (missing === 0) {') - indent++ - } - } - - if (node.uniqueItems) { - if (type !== 'array') validate('if (%s) {', types.array(name)) - validate('if (!(unique(%s))) {', name) - error('must be unique') - validate('}') - if (type !== 'array') validate('}') - } - - if (node.enum) { - var complex = node.enum.some(function(e) { - return typeof e === 'object' - }) - - var compare = complex ? - function(e) { - return 'JSON.stringify('+name+')'+' !== JSON.stringify('+JSON.stringify(e)+')' - } : - function(e) { - return name+' !== '+JSON.stringify(e) + if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object' || node === null) { + return json.stringify(node); } + if (isArray(node)) { + var out = []; + for (var i = 0; i < node.length; i++) { + var item = stringify(node, i, node[i], level + 1) || json.stringify(null); + out.push(indent + space + item); + } + return '[' + out.join(',') + indent + ']'; + } else { + if (seen.indexOf(node) !== -1) { + if (cycles) return json.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } else seen.push(node); - validate('if (%s) {', node.enum.map(compare).join(' && ') || 'false') - error('must be an enum value') - validate('}') - } - - if (node.dependencies) { - if (type !== 'object') validate('if (%s) {', types.object(name)) + var keys = objectKeys(node).sort(cmp && cmp(node)); + var out = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node, key, node[key], level + 1); - Object.keys(node.dependencies).forEach(function(key) { - var deps = node.dependencies[key] - if (typeof deps === 'string') deps = [deps] + if (!value) continue; - var exists = function(k) { - return genobj(name, k) + ' !== undefined' + var keyValue = json.stringify(key) + colonSeparator + value; + ; + out.push(indent + space + keyValue); + } + seen.splice(seen.indexOf(node), 1); + return '{' + out.join(',') + indent + '}'; } + }({ '': obj }, '', obj, 0); +}; - if (Array.isArray(deps)) { - validate('if (%s !== undefined && !(%s)) {', genobj(name, key), deps.map(exists).join(' && ') || 'true') - error('dependencies not set') - validate('}') - } - if (typeof deps === 'object') { - validate('if (%s !== undefined) {', genobj(name, key)) - visit(name, deps, reporter, filter) - validate('}') - } - }) +var isArray = Array.isArray || function (x) { + return {}.toString.call(x) === '[object Array]'; +}; - if (type !== 'object') validate('}') +var objectKeys = Object.keys || function (obj) { + var has = Object.prototype.hasOwnProperty || function () { + return true; + }; + var keys = []; + for (var key in obj) { + if (has.call(obj, key)) keys.push(key); } + return keys; +}; - if (node.additionalProperties || node.additionalProperties === false) { - if (type !== 'object') validate('if (%s) {', types.object(name)) - - var i = genloop() - var keys = gensym('keys') - - var toCompare = function(p) { - return keys+'['+i+'] !== '+JSON.stringify(p) - } - - var toTest = function(p) { - return '!'+patterns(p)+'.test('+keys+'['+i+'])' - } - - var additionalProp = Object.keys(properties || {}).map(toCompare) - .concat(Object.keys(node.patternProperties || {}).map(toTest)) - .join(' && ') || 'true' +},{"jsonify":86}],86:[function(require,module,exports){ +'use strict'; - validate('var %s = Object.keys(%s)', keys, name) - ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i) - ('if (%s) {', additionalProp) +exports.parse = require('./lib/parse'); +exports.stringify = require('./lib/stringify'); - if (node.additionalProperties === false) { - if (filter) validate('delete %s', name+'['+keys+'['+i+']]') - error('has additional properties', null, JSON.stringify(name+'.') + ' + ' + keys + '['+i+']') - } else { - visit(name+'['+keys+'['+i+']]', node.additionalProperties, reporter, filter) - } +},{"./lib/parse":87,"./lib/stringify":88}],87:[function(require,module,exports){ +'use strict'; - validate - ('}') - ('}') +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - if (type !== 'object') validate('}') +var at, + // The index of the current character +ch, + // The current character +escapee = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' +}, + text, + error = function error(m) { + // Call error when something is wrong. + throw { + name: 'SyntaxError', + message: m, + at: at, + text: text + }; +}, + next = function next(c) { + // If a c parameter is provided, verify that it matches the current character. + if (c && c !== ch) { + error("Expected '" + c + "' instead of '" + ch + "'"); + } + + // Get the next character. When there are no more characters, + // return the empty string. + + ch = text.charAt(at); + at += 1; + return ch; +}, + number = function number() { + // Parse a number value. + var number, + string = ''; + + if (ch === '-') { + string = '-'; + next('-'); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); } - - if (node.$ref) { - var sub = get(root, opts && opts.schemas || {}, node.$ref) - if (sub) { - var fn = cache[node.$ref] - if (!fn) { - cache[node.$ref] = function proxy(data) { - return fn(data) - } - fn = compile(sub, cache, root, false, opts) + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; } - var n = gensym('ref') - scope[n] = fn - validate('if (!(%s(%s))) {', n, name) - error('referenced schema does not match') - validate('}') - } - } - - if (node.not) { - var prev = gensym('prev') - validate('var %s = errors', prev) - visit(name, node.not, false, filter) - validate('if (%s === errors) {', prev) - error('negative schema matches') - validate('} else {') - ('errors = %s', prev) - ('}') - } - - if (node.items && !tuple) { - if (type !== 'array') validate('if (%s) {', types.array(name)) - - var i = genloop() - validate('for (var %s = 0; %s < %s.length; %s++) {', i, i, name, i) - visit(name+'['+i+']', node.items, reporter, filter) - validate('}') - - if (type !== 'array') validate('}') - } - - if (node.patternProperties) { - if (type !== 'object') validate('if (%s) {', types.object(name)) - var keys = gensym('keys') - var i = genloop() - validate - ('var %s = Object.keys(%s)', keys, name) - ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i) - - Object.keys(node.patternProperties).forEach(function(key) { - var p = patterns(key) - validate('if (%s.test(%s)) {', p, keys+'['+i+']') - visit(name+'['+keys+'['+i+']]', node.patternProperties[key], reporter, filter) - validate('}') - }) - - validate('}') - if (type !== 'object') validate('}') - } - - if (node.pattern) { - var p = patterns(node.pattern) - if (type !== 'string') validate('if (%s) {', types.string(name)) - validate('if (!(%s.test(%s))) {', p, name) - error('pattern mismatch') - validate('}') - if (type !== 'string') validate('}') } - - if (node.allOf) { - node.allOf.forEach(function(sch) { - visit(name, sch, reporter, filter) - }) + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } } - - if (node.anyOf && node.anyOf.length) { - var prev = gensym('prev') - - node.anyOf.forEach(function(sch, i) { - if (i === 0) { - validate('var %s = errors', prev) - } else { - validate('if (errors !== %s) {', prev) - ('errors = %s', prev) + number = +string; + if (!isFinite(number)) { + error("Bad number"); + } else { + return number; + } +}, + string = function string() { + // Parse a string value. + var hex, + i, + string = '', + uffff; + + // When parsing for string values, we must look for " and \ characters. + if (ch === '"') { + while (next()) { + if (ch === '"') { + next(); + return string; + } else if (ch === '\\') { + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + } else { + string += ch; + } } - visit(name, sch, false, false) - }) - node.anyOf.forEach(function(sch, i) { - if (i) validate('}') - }) - validate('if (%s !== errors) {', prev) - error('no schemas match') - validate('}') } + error("Bad string"); +}, + white = function white() { - if (node.oneOf && node.oneOf.length) { - var prev = gensym('prev') - var passes = gensym('passes') - - validate - ('var %s = errors', prev) - ('var %s = 0', passes) + // Skip whitespace. - node.oneOf.forEach(function(sch, i) { - visit(name, sch, false, false) - validate('if (%s === errors) {', prev) - ('%s++', passes) - ('} else {') - ('errors = %s', prev) - ('}') - }) - - validate('if (%s !== 1) {', passes) - error('no (or more than one) schemas match') - validate('}') + while (ch && ch <= ' ') { + next(); } +}, + word = function word() { - if (node.multipleOf !== undefined) { - if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name)) - - validate('if (!isMultipleOf(%s, %d)) {', name, node.multipleOf) - - error('has a remainder') - validate('}') + // true, false, or null. - if (type !== 'number' && type !== 'integer') validate('}') + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; } + error("Unexpected '" + ch + "'"); +}, + value, + // Place holder for the value function. - if (node.maxProperties !== undefined) { - if (type !== 'object') validate('if (%s) {', types.object(name)) +array = function array() { - validate('if (Object.keys(%s).length > %d) {', name, node.maxProperties) - error('has more properties than allowed') - validate('}') + // Parse an array value. - if (type !== 'object') validate('}') - } - - if (node.minProperties !== undefined) { - if (type !== 'object') validate('if (%s) {', types.object(name)) + var array = []; - validate('if (Object.keys(%s).length < %d) {', name, node.minProperties) - error('has less properties than allowed') - validate('}') - - if (type !== 'object') validate('}') + if (ch === '[') { + next('['); + white(); + if (ch === ']') { + next(']'); + return array; // empty array + } + while (ch) { + array.push(value()); + white(); + if (ch === ']') { + next(']'); + return array; + } + next(','); + white(); + } } + error("Bad array"); +}, + object = function object() { - if (node.maxItems !== undefined) { - if (type !== 'array') validate('if (%s) {', types.array(name)) + // Parse an object value. - validate('if (%s.length > %d) {', name, node.maxItems) - error('has more items than allowed') - validate('}') + var key, + object = {}; - if (type !== 'array') validate('}') + if (ch === '{') { + next('{'); + white(); + if (ch === '}') { + next('}'); + return object; // empty object + } + while (ch) { + key = string(); + white(); + next(':'); + if (Object.hasOwnProperty.call(object, key)) { + error('Duplicate key "' + key + '"'); + } + object[key] = value(); + white(); + if (ch === '}') { + next('}'); + return object; + } + next(','); + white(); + } } + error("Bad object"); +}; - if (node.minItems !== undefined) { - if (type !== 'array') validate('if (%s) {', types.array(name)) +value = function value() { - validate('if (%s.length < %d) {', name, node.minItems) - error('has less items than allowed') - validate('}') + // Parse a JSON value. It could be an object, an array, a string, a number, + // or a word. - if (type !== 'array') validate('}') + white(); + switch (ch) { + case '{': + return object(); + case '[': + return array(); + case '"': + return string(); + case '-': + return number(); + default: + return ch >= '0' && ch <= '9' ? number() : word(); } +}; - if (node.maxLength !== undefined) { - if (type !== 'string') validate('if (%s) {', types.string(name)) +// Return the json_parse function. It will have access to all of the above +// functions and variables. - validate('if (%s.length > %d) {', name, node.maxLength) - error('has longer length than allowed') - validate('}') +module.exports = function (source, reviver) { + var result; - if (type !== 'string') validate('}') - } + text = source; + at = 0; + ch = ' '; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } + + // If there is a reviver function, we recursively walk the new structure, + // passing each name/value pair to the reviver function for possible + // transformation, starting with a temporary root object that holds the result + // in an empty key. If there is not a reviver function, we simply return the + // result. + + return typeof reviver === 'function' ? function walk(holder, key) { + var k, + v, + value = holder[key]; + if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + }({ '': result }, '') : result; +}; - if (node.minLength !== undefined) { - if (type !== 'string') validate('if (%s) {', types.string(name)) +},{}],88:[function(require,module,exports){ +'use strict'; - validate('if (%s.length < %d) {', name, node.minLength) - error('has less length than allowed') - validate('}') +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - if (type !== 'string') validate('}') - } +var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"': '\\"', + '\\': '\\\\' +}, + rep; + +function quote(string) { + // If the string contains no control characters, no quote characters, and no + // backslash characters, then we can safely slap some quotes around it. + // Otherwise we must also replace the offending characters with safe escape + // sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; +} - if (node.minimum !== undefined) { - if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name)) +function str(key, holder) { + // Produce a string from holder[key]. + var i, + // The loop counter. + k, + // The member key. + v, + // The member value. + length, + mind = gap, + partial, + value = holder[key]; + + // If the value has a toJSON method, call it to obtain a replacement value. + if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + + // If we were called with a replacer function, then call the replacer to + // obtain a replacement value. + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + + // What happens next depends on the value's type. + switch (typeof value === 'undefined' ? 'undefined' : _typeof(value)) { + case 'string': + return quote(value); + + case 'number': + // JSON numbers must be finite. Encode non-finite numbers as null. + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + // If the value is a boolean or null, convert it to a string. Note: + // typeof null does not produce 'null'. The case is included here in + // the remote chance that this gets fixed someday. + return String(value); + + case 'object': + if (!value) return 'null'; + gap += indent; + partial = []; + + // Array.isArray + if (Object.prototype.toString.apply(value) === '[object Array]') { + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + + // Join all of the elements together, separated with commas, and + // wrap them in brackets. + v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + + // If the replacer is an array, use it to select the members to be + // stringified. + if (rep && (typeof rep === 'undefined' ? 'undefined' : _typeof(rep)) === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + k = rep[i]; + if (typeof k === 'string') { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + // Otherwise, iterate through all of the keys in the object. + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } - validate('if (%s %s %d) {', name, node.exclusiveMinimum ? '<=' : '<', node.minimum) - error('is less than minimum') - validate('}') + // Join all of the member texts together, separated with commas, + // and wrap them in braces. - if (type !== 'number' && type !== 'integer') validate('}') + v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; + gap = mind; + return v; } +} - if (node.maximum !== undefined) { - if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name)) - - validate('if (%s %s %d) {', name, node.exclusiveMaximum ? '>=' : '>', node.maximum) - error('is more than maximum') - validate('}') +module.exports = function (value, replacer, space) { + var i; + gap = ''; + indent = ''; - if (type !== 'number' && type !== 'integer') validate('}') + // If the space parameter is a number, make an indent string containing that + // many spaces. + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } } + // If the space parameter is a string, it will be used as the indent string. + else if (typeof space === 'string') { + indent = space; + } - if (properties) { - Object.keys(properties).forEach(function(p) { - if (Array.isArray(type) && type.indexOf('null') !== -1) validate('if (%s !== null) {', name) - - visit(genobj(name, p), properties[p], reporter, filter) - - if (Array.isArray(type) && type.indexOf('null') !== -1) validate('}') - }) + // If there is a replacer, it must be a function or an array. + // Otherwise, throw an error. + rep = replacer; + if (replacer && typeof replacer !== 'function' && ((typeof replacer === 'undefined' ? 'undefined' : _typeof(replacer)) !== 'object' || typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); } - while (indent--) validate('}') - } - - var validate = genfun - ('function validate(data) {') - // Since undefined is not a valid JSON value, we coerce to null and other checks will catch this - ('if (data === undefined) data = null') - ('validate.errors = null') - ('var errors = 0') - - visit('data', schema, reporter, opts && opts.filter) - - validate - ('return errors === 0') - ('}') - - validate = validate.toFunction(scope) - validate.errors = null - - if (Object.defineProperty) { - Object.defineProperty(validate, 'error', { - get: function() { - if (!validate.errors) return '' - return validate.errors.map(function(err) { - return err.field + ' ' + err.message; - }).join('\n') - } - }) - } - - validate.toJSON = function() { - return schema - } - - return validate -} - -module.exports = function(schema, opts) { - if (typeof schema === 'string') schema = JSON.parse(schema) - return compile(schema, {}, schema, true, opts) -} - -module.exports.filter = function(schema, opts) { - var validate = module.exports(schema, xtend(opts, {filter: true})) - return function(sch) { - validate(sch) - return sch - } -} - -},{"./formats":105,"generate-function":100,"generate-object-property":101,"jsonpointer":109,"xtend":130}],107:[function(require,module,exports){ -"use strict" -function isProperty(str) { - return /^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\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\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\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\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-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\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\u0d60\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-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\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\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\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\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\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][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\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\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\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\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-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\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\u0d60\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-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\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\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\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\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\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-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(str) -} -module.exports = isProperty -},{}],108:[function(require,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; + // Make a fake root object containing our value under the key of ''. + // Return the result of stringifying the value. + return str('', { '': value }); }; -},{}],109:[function(require,module,exports){ -var hasExcape = /~/ -var escapeMatcher = /~[01]/g -function escapeReplacer (m) { - switch (m) { - case '~1': return '/' - case '~0': return '~' - } - throw new Error('Invalid tilde escape: ' + m) -} - -function untilde (str) { - if (!hasExcape.test(str)) return str - return str.replace(escapeMatcher, escapeReplacer) -} - -function setter (obj, pointer, value) { - var part - var hasNextPart - - for (var p = 1, len = pointer.length; p < len;) { - part = untilde(pointer[p++]) - hasNextPart = len > p - - if (typeof obj[part] === 'undefined') { - // support setting of /- - if (Array.isArray(obj) && part === '-') { - part = obj.length - } - - // support nested objects/array when setting values - if (hasNextPart) { - if ((pointer[p] !== '' && pointer[p] < Infinity) || pointer[p] === '-') obj[part] = [] - else obj[part] = {} - } - } - - if (!hasNextPart) break - obj = obj[part] - } - - var oldValue = obj[part] - if (value === undefined) delete obj[part] - else obj[part] = value - return oldValue -} - -function compilePointer (pointer) { - if (typeof pointer === 'string') { - pointer = pointer.split('/') - if (pointer[0] === '') return pointer - throw new Error('Invalid JSON pointer.') - } else if (Array.isArray(pointer)) { - return pointer - } - - throw new Error('Invalid JSON pointer.') -} - -function get (obj, pointer) { - if (typeof obj !== 'object') throw new Error('Invalid input object.') - pointer = compilePointer(pointer) - var len = pointer.length - if (len === 1) return obj - - for (var p = 1; p < len;) { - obj = obj[untilde(pointer[p++])] - if (len === p) return obj - if (typeof obj !== 'object') return undefined - } -} - -function set (obj, pointer, value) { - if (typeof obj !== 'object') throw new Error('Invalid input object.') - pointer = compilePointer(pointer) - if (pointer.length === 0) throw new Error('Invalid JSON pointer for set.') - return setter(obj, pointer, value) -} - -function compile (pointer) { - var compiled = compilePointer(pointer) - return { - get: function (object) { - return get(object, compiled) - }, - set: function (object, value) { - return set(object, compiled, value) - } - } -} - -exports.get = get -exports.set = set -exports.compile = compile +},{}],89:[function(require,module,exports){ +'use strict'; -},{}],110:[function(require,module,exports){ // Generated by LiveScript 1.4.0 -(function(){ - var parsedTypeCheck, types, toString$ = {}.toString; +(function () { + var parsedTypeCheck, + types, + toString$ = {}.toString; parsedTypeCheck = require('type-check').parsedTypeCheck; types = { - '*': function(value, options){ + '*': function _(value, options) { switch (toString$.call(value).slice(8, -1)) { - case 'Array': - return typeCast(value, { - type: 'Array' - }, options); - case 'Object': - return typeCast(value, { - type: 'Object' - }, options); - default: - return { - type: 'Just', - value: typesCast(value, [ - { + case 'Array': + return typeCast(value, { + type: 'Array' + }, options); + case 'Object': + return typeCast(value, { + type: 'Object' + }, options); + default: + return { + type: 'Just', + value: typesCast(value, [{ type: 'Undefined' }, { type: 'Null' @@ -29067,12 +34176,11 @@ exports.compile = compile type: 'Object' }, { type: 'String' - } - ], (options.explicit = true, options)) - }; + }], (options.explicit = true, options)) + }; } }, - Undefined: function(it){ + Undefined: function Undefined(it) { if (it === 'undefined' || it === void 8) { return { type: 'Just', @@ -29084,7 +34192,7 @@ exports.compile = compile }; } }, - Null: function(it){ + Null: function Null(it) { if (it === 'null') { return { type: 'Just', @@ -29096,7 +34204,17 @@ exports.compile = compile }; } }, - NaN: function(it){ + NaN: function (_NaN) { + function NaN(_x) { + return _NaN.apply(this, arguments); + } + + NaN.toString = function () { + return _NaN.toString(); + }; + + return NaN; + }(function (it) { if (it === 'NaN') { return { type: 'Just', @@ -29107,8 +34225,8 @@ exports.compile = compile type: 'Nothing' }; } - }, - Boolean: function(it){ + }), + Boolean: function Boolean(it) { if (it === 'true') { return { type: 'Just', @@ -29125,25 +34243,35 @@ exports.compile = compile }; } }, - Number: function(it){ + Number: function Number(it) { return { type: 'Just', value: +it }; }, - Int: function(it){ + Int: function Int(it) { return { type: 'Just', value: +it }; }, - Float: function(it){ + Float: function Float(it) { return { type: 'Just', value: +it }; }, - Date: function(value, options){ + Date: function (_Date) { + function Date(_x2, _x3) { + return _Date.apply(this, arguments); + } + + Date.toString = function () { + return _Date.toString(); + }; + + return Date; + }(function (value, options) { var that; if (that = /^\#([\s\S]*)\#$/.exec(value)) { return { @@ -29160,8 +34288,18 @@ exports.compile = compile value: new Date(+value || value) }; } - }, - RegExp: function(value, options){ + }), + RegExp: function (_RegExp) { + function RegExp(_x4, _x5) { + return _RegExp.apply(this, arguments); + } + + RegExp.toString = function () { + return _RegExp.toString(); + }; + + return RegExp; + }(function (value, options) { var that; if (that = /^\/([\s\S]*)\/([gimy]*)$/.exec(value)) { return { @@ -29178,20 +34316,20 @@ exports.compile = compile value: new RegExp(value) }; } - }, - Array: function(value, options){ + }), + Array: function Array(value, options) { return castArray(value, { of: [{ type: '*' }] }, options); }, - Object: function(value, options){ + Object: function Object(value, options) { return castFields(value, { of: {} }, options); }, - String: function(it){ + String: function String(it) { var that; if (toString$.call(it).slice(8, -1) !== 'String') { return { @@ -29216,7 +34354,7 @@ exports.compile = compile } } }; - function castArray(node, type, options){ + function castArray(node, type, options) { var typeOf, element; if (toString$.call(node).slice(8, -1) !== 'Array') { return { @@ -29226,17 +34364,20 @@ exports.compile = compile typeOf = type.of; return { type: 'Just', - value: (function(){ - var i$, ref$, len$, results$ = []; + value: function () { + var i$, + ref$, + len$, + results$ = []; for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) { element = ref$[i$]; results$.push(typesCast(element, typeOf, options)); } return results$; - }()) + }() }; } - function castTuple(node, type, options){ + function castTuple(node, type, options) { var result, i, i$, ref$, len$, types, cast; if (toString$.call(node).slice(8, -1) !== 'Array') { return { @@ -29264,7 +34405,7 @@ exports.compile = compile }; } } - function castFields(node, type, options){ + function castFields(node, type, options) { var typeOf, key, value; if (toString$.call(node).slice(8, -1) !== 'Object') { return { @@ -29274,8 +34415,9 @@ exports.compile = compile typeOf = type.of; return { type: 'Just', - value: (function(){ - var ref$, resultObj$ = {}; + value: function () { + var ref$, + resultObj$ = {}; for (key in ref$ = node) { value = ref$[key]; resultObj$[typesCast(key, [{ @@ -29285,10 +34427,10 @@ exports.compile = compile }], options); } return resultObj$; - }()) + }() }; } - function typeCast(node, typeObj, options){ + function typeCast(node, typeObj, options) { var type, structure, castFunc, ref$; type = typeObj.type, structure = typeObj.structure; if (type) { @@ -29299,16 +34441,16 @@ exports.compile = compile return castFunc(node, options, typesCast); } else { switch (structure) { - case 'array': - return castArray(node, typeObj, options); - case 'tuple': - return castTuple(node, typeObj, options); - case 'fields': - return castFields(node, typeObj, options); + case 'array': + return castArray(node, typeObj, options); + case 'tuple': + return castTuple(node, typeObj, options); + case 'fields': + return castFields(node, typeObj, options); } } } - function typesCast(node, types, options){ + function typesCast(node, types, options) { var i$, len$, type, ref$, valueType, value; for (i$ = 0, len$ = types.length; i$ < len$; ++i$) { type = types[i$]; @@ -29325,23 +34467,25 @@ exports.compile = compile throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + "."); } module.exports = typesCast; -}).call(this); +}).call(undefined); + +},{"type-check":110}],90:[function(require,module,exports){ +'use strict'; -},{"type-check":125}],111:[function(require,module,exports){ // Generated by LiveScript 1.4.0 -(function(){ +(function () { var parseString, cast, parseType, VERSION, parsedTypeParse, parse; parseString = require('./parse-string'); cast = require('./cast'); parseType = require('type-check').parseType; VERSION = '0.3.0'; - parsedTypeParse = function(parsedType, string, options){ + parsedTypeParse = function parsedTypeParse(parsedType, string, options) { options == null && (options = {}); options.explicit == null && (options.explicit = false); options.customTypes == null && (options.customTypes = {}); return cast(parseString(parsedType, string, options), parsedType, options); }; - parse = function(type, string, options){ + parse = function parse(type, string, options) { return parsedTypeParse(parseType(type), string, options); }; module.exports = { @@ -29349,26 +34493,28 @@ exports.compile = compile parse: parse, parsedTypeParse: parsedTypeParse }; -}).call(this); +}).call(undefined); + +},{"./cast":89,"./parse-string":91,"type-check":110}],91:[function(require,module,exports){ +"use strict"; -},{"./cast":110,"./parse-string":112,"type-check":125}],112:[function(require,module,exports){ // Generated by LiveScript 1.4.0 -(function(){ +(function () { var reject, special, tokenRegex; reject = require('prelude-ls').reject; - function consumeOp(tokens, op){ + function consumeOp(tokens, op) { if (tokens[0] === op) { return tokens.shift(); } else { throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + "."); } } - function maybeConsumeOp(tokens, op){ + function maybeConsumeOp(tokens, op) { if (tokens[0] === op) { return tokens.shift(); } } - function consumeList(tokens, arg$, hasDelimiters){ + function consumeList(tokens, arg$, hasDelimiters) { var open, close, result, untilTest; open = arg$[0], close = arg$[1]; if (hasDelimiters) { @@ -29376,7 +34522,7 @@ exports.compile = compile } result = []; untilTest = "," + (hasDelimiters ? close : ''); - while (tokens.length && (hasDelimiters && tokens[0] !== close)) { + while (tokens.length && hasDelimiters && tokens[0] !== close) { result.push(consumeElement(tokens, untilTest)); maybeConsumeOp(tokens, ','); } @@ -29385,13 +34531,13 @@ exports.compile = compile } return result; } - function consumeArray(tokens, hasDelimiters){ + function consumeArray(tokens, hasDelimiters) { return consumeList(tokens, ['[', ']'], hasDelimiters); } - function consumeTuple(tokens, hasDelimiters){ + function consumeTuple(tokens, hasDelimiters) { return consumeList(tokens, ['(', ')'], hasDelimiters); } - function consumeFields(tokens, hasDelimiters){ + function consumeFields(tokens, hasDelimiters) { var result, untilTest, key; if (hasDelimiters) { consumeOp(tokens, '{'); @@ -29409,7 +34555,7 @@ exports.compile = compile } return result; } - function consumeValue(tokens, untilTest){ + function consumeValue(tokens, untilTest) { var out; untilTest == null && (untilTest = ''); out = ''; @@ -29418,31 +34564,25 @@ exports.compile = compile } return out; } - function consumeElement(tokens, untilTest){ + function consumeElement(tokens, untilTest) { switch (tokens[0]) { - case '[': - return consumeArray(tokens, true); - case '(': - return consumeTuple(tokens, true); - case '{': - return consumeFields(tokens, true); - default: - return consumeValue(tokens, untilTest); + case '[': + return consumeArray(tokens, true); + case '(': + return consumeTuple(tokens, true); + case '{': + return consumeFields(tokens, true); + default: + return consumeValue(tokens, untilTest); } } - function consumeTopLevel(tokens, types, options){ + function consumeTopLevel(tokens, types, options) { var ref$, type, structure, origTokens, result, finalResult, x$, y$; ref$ = types[0], type = ref$.type, structure = ref$.structure; origTokens = tokens.concat(); - if (!options.explicit && types.length === 1 && ((!type && structure) || (type === 'Array' || type === 'Object'))) { - result = structure === 'array' || type === 'Array' - ? consumeArray(tokens, tokens[0] === '[') - : structure === 'tuple' - ? consumeTuple(tokens, tokens[0] === '(') - : consumeFields(tokens, tokens[0] === '{'); - finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array' - ? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$) - : (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result; + if (!options.explicit && types.length === 1 && (!type && structure || type === 'Array' || type === 'Object')) { + result = structure === 'array' || type === 'Array' ? consumeArray(tokens, tokens[0] === '[') : structure === 'tuple' ? consumeTuple(tokens, tokens[0] === '(') : consumeFields(tokens, tokens[0] === '{'); + finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array' ? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$) : (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result; } else { finalResult = consumeElement(tokens); } @@ -29450,7 +34590,7 @@ exports.compile = compile } special = /\[\]\(\)}{:,/.source; tokenRegex = RegExp('("(?:\\\\"|[^"])*")|(\'(?:\\\\\'|[^\'])*\')|(/(?:\\\\/|[^/])*/[a-zA-Z]*)|(#.*#)|([' + special + '])|([^\\s' + special + '](?:\\s*[^\\s' + special + ']+)*)|\\s*'); - module.exports = function(types, string, options){ + module.exports = function (types, string, options) { var tokens, node; options == null && (options = {}); if (!options.explicit && types.length === 1 && types[0].type === 'String') { @@ -29463,493 +34603,48 @@ exports.compile = compile } return node; }; - function not$(x){ return !x; } -}).call(this); + function not$(x) { + return !x; + } +}).call(undefined); -},{"prelude-ls":122}],113:[function(require,module,exports){ +},{"prelude-ls":103}],92:[function(require,module,exports){ (function (global){ -/** +'use strict';var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};/** * @license * Lodash * Copyright JS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '4.17.4'; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function'; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; - - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - reLeadingDot = /^\./, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** + */;(function(){/** Used as a safe reference for `undefined` in pre-ES5 environments. */var undefined;/** Used as the semantic version number. */var VERSION='4.17.4';/** Used as the size to enable large array optimizations. */var LARGE_ARRAY_SIZE=200;/** Error message constants. */var CORE_ERROR_TEXT='Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',FUNC_ERROR_TEXT='Expected a function';/** Used to stand-in for `undefined` hash values. */var HASH_UNDEFINED='__lodash_hash_undefined__';/** Used as the maximum memoize cache size. */var MAX_MEMOIZE_SIZE=500;/** Used as the internal argument placeholder. */var PLACEHOLDER='__lodash_placeholder__';/** Used to compose bitmasks for cloning. */var CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4;/** Used to compose bitmasks for value comparisons. */var COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;/** Used to compose bitmasks for function metadata. */var WRAP_BIND_FLAG=1,WRAP_BIND_KEY_FLAG=2,WRAP_CURRY_BOUND_FLAG=4,WRAP_CURRY_FLAG=8,WRAP_CURRY_RIGHT_FLAG=16,WRAP_PARTIAL_FLAG=32,WRAP_PARTIAL_RIGHT_FLAG=64,WRAP_ARY_FLAG=128,WRAP_REARG_FLAG=256,WRAP_FLIP_FLAG=512;/** Used as default options for `_.truncate`. */var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION='...';/** Used to detect hot functions by number of calls within a span of milliseconds. */var HOT_COUNT=800,HOT_SPAN=16;/** Used to indicate the type of lazy iteratees. */var LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3;/** Used as references for various `Number` constants. */var INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e+308,NAN=0/0;/** Used as references for the maximum length and index of an array. */var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;/** Used to associate wrap methods with their bit flags. */var wrapFlags=[['ary',WRAP_ARY_FLAG],['bind',WRAP_BIND_FLAG],['bindKey',WRAP_BIND_KEY_FLAG],['curry',WRAP_CURRY_FLAG],['curryRight',WRAP_CURRY_RIGHT_FLAG],['flip',WRAP_FLIP_FLAG],['partial',WRAP_PARTIAL_FLAG],['partialRight',WRAP_PARTIAL_RIGHT_FLAG],['rearg',WRAP_REARG_FLAG]];/** `Object#toString` result references. */var argsTag='[object Arguments]',arrayTag='[object Array]',asyncTag='[object AsyncFunction]',boolTag='[object Boolean]',dateTag='[object Date]',domExcTag='[object DOMException]',errorTag='[object Error]',funcTag='[object Function]',genTag='[object GeneratorFunction]',mapTag='[object Map]',numberTag='[object Number]',nullTag='[object Null]',objectTag='[object Object]',promiseTag='[object Promise]',proxyTag='[object Proxy]',regexpTag='[object RegExp]',setTag='[object Set]',stringTag='[object String]',symbolTag='[object Symbol]',undefinedTag='[object Undefined]',weakMapTag='[object WeakMap]',weakSetTag='[object WeakSet]';var arrayBufferTag='[object ArrayBuffer]',dataViewTag='[object DataView]',float32Tag='[object Float32Array]',float64Tag='[object Float64Array]',int8Tag='[object Int8Array]',int16Tag='[object Int16Array]',int32Tag='[object Int32Array]',uint8Tag='[object Uint8Array]',uint8ClampedTag='[object Uint8ClampedArray]',uint16Tag='[object Uint16Array]',uint32Tag='[object Uint32Array]';/** Used to match empty string literals in compiled template source. */var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;/** Used to match HTML entities and HTML characters. */var reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);/** Used to match template delimiters. */var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;/** Used to match property names within property paths. */var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;/** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); - - /** Used to match leading and trailing whitespace. */ - var reTrim = /^\s+|\s+$/g, - reTrimStart = /^\s+/, - reTrimEnd = /\s+$/; - - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; - - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** + */var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);/** Used to match leading and trailing whitespace. */var reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/;/** Used to match wrap detail comments. */var reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /;/** Used to match words composed of alphanumeric characters. */var reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;/** Used to match backslashes in property paths. */var reEscapeChar=/\\(\\)?/g;/** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; - - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', - rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); - - /** + */var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;/** Used to match `RegExp` flags from their coerced string values. */var reFlags=/\w*$/;/** Used to detect bad signed hexadecimal string values. */var reIsBadHex=/^[-+]0x[0-9a-f]+$/i;/** Used to detect binary string values. */var reIsBinary=/^0b[01]+$/i;/** Used to detect host constructors (Safari). */var reIsHostCtor=/^\[object .+?Constructor\]$/;/** Used to detect octal string values. */var reIsOctal=/^0o[0-7]+$/i;/** Used to detect unsigned integer values. */var reIsUint=/^(?:0|[1-9]\d*)$/;/** Used to match Latin Unicode letters (excluding mathematical operators). */var reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;/** Used to ensure capturing order of template delimiters. */var reNoMatch=/($^)/;/** Used to match unescaped characters in compiled string literals. */var reUnescapedString=/['\n\r\u2028\u2029\\]/g;/** Used to compose unicode character classes. */var rsAstralRange='\\ud800-\\udfff',rsComboMarksRange='\\u0300-\\u036f',reComboHalfMarksRange='\\ufe20-\\ufe2f',rsComboSymbolsRange='\\u20d0-\\u20ff',rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsDingbatRange='\\u2700-\\u27bf',rsLowerRange='a-z\\xdf-\\xf6\\xf8-\\xff',rsMathOpRange='\\xac\\xb1\\xd7\\xf7',rsNonCharRange='\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',rsPunctuationRange='\\u2000-\\u206f',rsSpaceRange=' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',rsUpperRange='A-Z\\xc0-\\xd6\\xd8-\\xde',rsVarRange='\\ufe0e\\ufe0f',rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange;/** Used to compose unicode capture groups. */var rsApos='[\'\u2019]',rsAstral='['+rsAstralRange+']',rsBreak='['+rsBreakRange+']',rsCombo='['+rsComboRange+']',rsDigits='\\d+',rsDingbat='['+rsDingbatRange+']',rsLower='['+rsLowerRange+']',rsMisc='[^'+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+']',rsFitz='\\ud83c[\\udffb-\\udfff]',rsModifier='(?:'+rsCombo+'|'+rsFitz+')',rsNonAstral='[^'+rsAstralRange+']',rsRegional='(?:\\ud83c[\\udde6-\\uddff]){2}',rsSurrPair='[\\ud800-\\udbff][\\udc00-\\udfff]',rsUpper='['+rsUpperRange+']',rsZWJ='\\u200d';/** Used to compose unicode regexes. */var rsMiscLower='(?:'+rsLower+'|'+rsMisc+')',rsMiscUpper='(?:'+rsUpper+'|'+rsMisc+')',rsOptContrLower='(?:'+rsApos+'(?:d|ll|m|re|s|t|ve))?',rsOptContrUpper='(?:'+rsApos+'(?:D|LL|M|RE|S|T|VE))?',reOptMod=rsModifier+'?',rsOptVar='['+rsVarRange+']?',rsOptJoin='(?:'+rsZWJ+'(?:'+[rsNonAstral,rsRegional,rsSurrPair].join('|')+')'+rsOptVar+reOptMod+')*',rsOrdLower='\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)',rsOrdUpper='\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)',rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji='(?:'+[rsDingbat,rsRegional,rsSurrPair].join('|')+')'+rsSeq,rsSymbol='(?:'+[rsNonAstral+rsCombo+'?',rsCombo,rsRegional,rsSurrPair,rsAstral].join('|')+')';/** Used to match apostrophes. */var reApos=RegExp(rsApos,'g');/** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; - - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; - - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; - - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /*--------------------------------------------------------------------------*/ - - /** + */var reComboMark=RegExp(rsCombo,'g');/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */var reUnicode=RegExp(rsFitz+'(?='+rsFitz+')|'+rsSymbol+rsSeq,'g');/** Used to match complex or compound words. */var reUnicodeWord=RegExp([rsUpper+'?'+rsLower+'+'+rsOptContrLower+'(?='+[rsBreak,rsUpper,'$'].join('|')+')',rsMiscUpper+'+'+rsOptContrUpper+'(?='+[rsBreak,rsUpper+rsMiscLower,'$'].join('|')+')',rsUpper+'?'+rsMiscLower+'+'+rsOptContrLower,rsUpper+'+'+rsOptContrUpper,rsOrdUpper,rsOrdLower,rsDigits,rsEmoji].join('|'),'g');/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */var reHasUnicode=RegExp('['+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+']');/** Used to detect strings that need a more robust regexp to match words. */var reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;/** Used to assign default `context` object properties. */var contextProps=['Array','Buffer','DataView','Date','Error','Float32Array','Float64Array','Function','Int8Array','Int16Array','Int32Array','Map','Math','Object','Promise','RegExp','Set','String','Symbol','TypeError','Uint8Array','Uint8ClampedArray','Uint16Array','Uint32Array','WeakMap','_','clearTimeout','isFinite','parseInt','setTimeout'];/** Used to make template sourceURLs easier to identify. */var templateCounter=-1;/** Used to identify `toStringTag` values of typed arrays. */var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;/** Used to identify `toStringTag` values supported by `_.clone`. */var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=false;/** Used to map Latin Unicode letters to basic Latin letters. */var deburredLetters={// Latin-1 Supplement block. +'\xc0':'A','\xc1':'A','\xc2':'A','\xc3':'A','\xc4':'A','\xc5':'A','\xe0':'a','\xe1':'a','\xe2':'a','\xe3':'a','\xe4':'a','\xe5':'a','\xc7':'C','\xe7':'c','\xd0':'D','\xf0':'d','\xc8':'E','\xc9':'E','\xca':'E','\xcb':'E','\xe8':'e','\xe9':'e','\xea':'e','\xeb':'e','\xcc':'I','\xcd':'I','\xce':'I','\xcf':'I','\xec':'i','\xed':'i','\xee':'i','\xef':'i','\xd1':'N','\xf1':'n','\xd2':'O','\xd3':'O','\xd4':'O','\xd5':'O','\xd6':'O','\xd8':'O','\xf2':'o','\xf3':'o','\xf4':'o','\xf5':'o','\xf6':'o','\xf8':'o','\xd9':'U','\xda':'U','\xdb':'U','\xdc':'U','\xf9':'u','\xfa':'u','\xfb':'u','\xfc':'u','\xdd':'Y','\xfd':'y','\xff':'y','\xc6':'Ae','\xe6':'ae','\xde':'Th','\xfe':'th','\xdf':'ss',// Latin Extended-A block. +'\u0100':'A','\u0102':'A','\u0104':'A','\u0101':'a','\u0103':'a','\u0105':'a','\u0106':'C','\u0108':'C','\u010A':'C','\u010C':'C','\u0107':'c','\u0109':'c','\u010B':'c','\u010D':'c','\u010E':'D','\u0110':'D','\u010F':'d','\u0111':'d','\u0112':'E','\u0114':'E','\u0116':'E','\u0118':'E','\u011A':'E','\u0113':'e','\u0115':'e','\u0117':'e','\u0119':'e','\u011B':'e','\u011C':'G','\u011E':'G','\u0120':'G','\u0122':'G','\u011D':'g','\u011F':'g','\u0121':'g','\u0123':'g','\u0124':'H','\u0126':'H','\u0125':'h','\u0127':'h','\u0128':'I','\u012A':'I','\u012C':'I','\u012E':'I','\u0130':'I','\u0129':'i','\u012B':'i','\u012D':'i','\u012F':'i','\u0131':'i','\u0134':'J','\u0135':'j','\u0136':'K','\u0137':'k','\u0138':'k','\u0139':'L','\u013B':'L','\u013D':'L','\u013F':'L','\u0141':'L','\u013A':'l','\u013C':'l','\u013E':'l','\u0140':'l','\u0142':'l','\u0143':'N','\u0145':'N','\u0147':'N','\u014A':'N','\u0144':'n','\u0146':'n','\u0148':'n','\u014B':'n','\u014C':'O','\u014E':'O','\u0150':'O','\u014D':'o','\u014F':'o','\u0151':'o','\u0154':'R','\u0156':'R','\u0158':'R','\u0155':'r','\u0157':'r','\u0159':'r','\u015A':'S','\u015C':'S','\u015E':'S','\u0160':'S','\u015B':'s','\u015D':'s','\u015F':'s','\u0161':'s','\u0162':'T','\u0164':'T','\u0166':'T','\u0163':'t','\u0165':'t','\u0167':'t','\u0168':'U','\u016A':'U','\u016C':'U','\u016E':'U','\u0170':'U','\u0172':'U','\u0169':'u','\u016B':'u','\u016D':'u','\u016F':'u','\u0171':'u','\u0173':'u','\u0174':'W','\u0175':'w','\u0176':'Y','\u0177':'y','\u0178':'Y','\u0179':'Z','\u017B':'Z','\u017D':'Z','\u017A':'z','\u017C':'z','\u017E':'z','\u0132':'IJ','\u0133':'ij','\u0152':'Oe','\u0153':'oe','\u0149':"'n",'\u017F':'s'};/** Used to map characters to HTML entities. */var htmlEscapes={'&':'&','<':'<','>':'>','"':'"',"'":'''};/** Used to map HTML entities to characters. */var htmlUnescapes={'&':'&','<':'<','>':'>','"':'"',''':"'"};/** Used to escape characters for inclusion in compiled string literals. */var stringEscapes={'\\':'\\',"'":"'",'\n':'n','\r':'r','\u2028':'u2028','\u2029':'u2029'};/** Built-in method references without a dependency on `root`. */var freeParseFloat=parseFloat,freeParseInt=parseInt;/** Detect free variable `global` from Node.js. */var freeGlobal=(typeof global==='undefined'?'undefined':_typeof(global))=='object'&&global&&global.Object===Object&&global;/** Detect free variable `self`. */var freeSelf=(typeof self==='undefined'?'undefined':_typeof(self))=='object'&&self&&self.Object===Object&&self;/** Used as a reference to the global object. */var root=freeGlobal||freeSelf||Function('return this')();/** Detect free variable `exports`. */var freeExports=(typeof exports==='undefined'?'undefined':_typeof(exports))=='object'&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule=freeExports&&(typeof module==='undefined'?'undefined':_typeof(module))=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports=freeModule&&freeModule.exports===freeExports;/** Detect free variable `process` from Node.js. */var freeProcess=moduleExports&&freeGlobal.process;/** Used to access faster Node.js helpers. */var nodeUtil=function(){try{return freeProcess&&freeProcess.binding&&freeProcess.binding('util');}catch(e){}}();/* Node.js helper references. */var nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;/*--------------------------------------------------------------------------*//** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } - - /** + */function addMapEntry(map,pair){// Don't return `map.set` because it's not chainable in IE 11. +map.set(pair[0],pair[1]);return map;}/** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - - /** + */function addSetEntry(set,value){// Don't return `set.add` because it's not chainable in IE 11. +set.add(value);return set;}/** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * @@ -29958,18 +34653,7 @@ exports.compile = compile * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /** + */function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2]);}return func.apply(thisArg,args);}/** * A specialized version of `baseAggregator` for arrays. * * @private @@ -29978,19 +34662,7 @@ exports.compile = compile * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } - - /** + */function arrayAggregator(array,setter,iteratee,accumulator){var index=-1,length=array==null?0:array.length;while(++index -1; - } - - /** + */function arrayIncludes(array,value){var length=array==null?0:array.length;return!!length&&baseIndexOf(array,value,0)>-1;}/** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private @@ -30099,20 +34711,7 @@ exports.compile = compile * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } - - /** + */function arrayIncludesWith(array,value,comparator){var index=-1,length=array==null?0:array.length;while(++index -1) {} - return index; - } - - /** + */function charsStartIndex(strSymbols,chrSymbols){var index=-1,length=strSymbols.length;while(++index-1){}return index;}/** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * @@ -30550,147 +34921,71 @@ exports.compile = compile * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** + */function charsEndIndex(strSymbols,chrSymbols){var index=strSymbols.length;while(index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index;}/** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; - - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - - /** + */function countHolders(array,placeholder){var length=array.length,result=0;while(length--){if(array[length]===placeholder){++result;}}return result;}/** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); - - /** + */var deburrLetter=basePropertyOf(deburredLetters);/** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); - - /** + */var escapeHtmlChar=basePropertyOf(htmlEscapes);/** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } - - /** + */function escapeStringChar(chr){return'\\'+stringEscapes[chr];}/** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** + */function getValue(object,key){return object==null?undefined:object[key];}/** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } - - /** + */function hasUnicode(string){return reHasUnicode.test(string);}/** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - - /** + */function hasUnicodeWord(string){return reHasUnicodeWord.test(string);}/** * Converts `iterator` to an array. * * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; - - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } - - /** + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */function iteratorToArray(iterator){var data,result=[];while(!(data=iterator.next()).done){result.push(data.value);}return result;}/** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** + */function mapToArray(map){var index=-1,result=Array(map.size);map.forEach(function(value,key){result[++index]=[key,value];});return result;}/** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** + */function overArg(func,transform){return function(arg){return func(transform(arg));};}/** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * @@ -30698,58 +34993,19 @@ exports.compile = compile * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } - - /** + */function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=0,result=[];while(++index 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper){return value;}if(hasOwnProperty.call(value,'__wrapped__')){return wrapperClone(value);}}return new LodashWrapper(value);}/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */var baseCreate=function(){function object(){}return function(proto){if(!isObject(proto)){return{};}if(objectCreate){return objectCreate(proto);}object.prototype=proto;var result=new object();object.prototype=undefined;return result;};}();/** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */function baseLodash(){}// No operation performed. +/** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */function LodashWrapper(value,chainAll){this.__wrapped__=value;this.__actions__=[];this.__chain__=!!chainAll;this.__index__=0;this.__values__=undefined;}/** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */lodash.templateSettings={/** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */'escape':reEscape,/** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */'evaluate':reEvaluate,/** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */'interpolate':reInterpolate,/** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */'variable':'',/** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */'imports':{/** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */'_':lodash}};// Ensure wrappers are instances of `baseLodash`. +lodash.prototype=baseLodash.prototype;lodash.prototype.constructor=lodash;LodashWrapper.prototype=baseCreate(baseLodash.prototype);LodashWrapper.prototype.constructor=LodashWrapper;/*------------------------------------------------------------------------*//** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */function LazyWrapper(value){this.__wrapped__=value;this.__actions__=[];this.__dir__=1;this.__filtered__=false;this.__iteratees__=[];this.__takeCount__=MAX_ARRAY_LENGTH;this.__views__=[];}/** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */function lazyClone(){var result=new LazyWrapper(this.__wrapped__);result.__actions__=copyArray(this.__actions__);result.__dir__=this.__dir__;result.__filtered__=this.__filtered__;result.__iteratees__=copyArray(this.__iteratees__);result.__takeCount__=this.__takeCount__;result.__views__=copyArray(this.__views__);return result;}/** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1;result.__filtered__=true;}else{result=this.clone();result.__dir__*=-1;}return result;}/** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=dir<0,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||!isRight&&arrLength==length&&takeCount==length){return baseWrapperValue(array,this.__actions__);}var result=[];outer:while(length--&&resIndex-1;}/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){++this.size;data.push([key,value]);}else{data[index][1]=value;}return this;}// Add methods to `ListCache`. +ListCache.prototype.clear=listCacheClear;ListCache.prototype['delete']=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;/*------------------------------------------------------------------------*//** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */function MapCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index=lower?number:lower;}}return number;}/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */function baseClone(value,bitmask,customizer,key,object,stack){var result,isDeep=bitmask&CLONE_DEEP_FLAG,isFlat=bitmask&CLONE_FLAT_FLAG,isFull=bitmask&CLONE_SYMBOLS_FLAG;if(customizer){result=object?customizer(value,key,object,stack):customizer(value);}if(result!==undefined){return result;}if(!isObject(value)){return value;}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return copyArray(value,result);}}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value)){return cloneBuffer(value,isDeep);}if(tag==objectTag||tag==argsTag||isFunc&&!object){result=isFlat||isFunc?{}:initCloneObject(value);if(!isDeep){return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value));}}else{if(!cloneableTags[tag]){return object?value:{};}result=initCloneByTag(value,tag,baseClone,isDeep);}}// Check for circular references and return its corresponding clone. +stack||(stack=new Stack());var stacked=stack.get(value);if(stacked){return stacked;}stack.set(value,result);var keysFunc=isFull?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys;var props=isArr?undefined:keysFunc(value);arrayEach(props||value,function(subValue,key){if(props){key=subValue;subValue=value[key];}// Recursively populate clone (susceptible to call stack limits). +assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack));});return result;}/** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props);};}/** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */function baseConformsTo(object,source,props){var length=props.length;if(object==null){return!length;}object=Object(object);while(length--){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value)){return false;}}return true;}/** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */function baseDelay(func,wait,args){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return setTimeout(function(){func.apply(undefined,args);},wait);}/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=true,length=array.length,result=[],valuesLength=values.length;if(!length){return result;}if(iteratee){values=arrayMap(values,baseUnary(iteratee));}if(comparator){includes=arrayIncludesWith;isCommon=false;}else if(values.length>=LARGE_ARRAY_SIZE){includes=cacheHas;isCommon=false;values=new SetCache(values);}outer:while(++indexlength?0:length+start;}end=end===undefined||end>length?length:toInteger(end);if(end<0){end+=length;}end=start>end?0:toLength(end);while(start0&&predicate(value)){if(depth>1){// Recursively flatten arrays (susceptible to call stack limits). +baseFlatten(value,depth-1,predicate,isStrict,result);}else{arrayPush(result,value);}}else if(!isStrict){result[result.length]=value;}}return result;}/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */var baseFor=createBaseFor();/** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */var baseForRight=createBaseFor(true);/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys);}/** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys);}/** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key]);});}/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */function baseGet(object,path){path=castPath(path,object);var index=0,length=path.length;while(object!=null&&indexother;}/** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */function baseHas(object,key){return object!=null&&hasOwnProperty.call(object,key);}/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */function baseHasIn(object,key){return object!=null&&key in Object(object);}/** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined;}array=arrays[0];var index=-1,seen=caches[0];outer:while(++index-1){if(seen!==array){splice.call(seen,fromIndex,1);}splice.call(array,fromIndex,1);}}return array;}/** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */function basePullAt(array,indexes){var length=array?indexes.length:0,lastIndex=length-1;while(length--){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index)){splice.call(array,index,1);}else{baseUnset(array,index);}}}return array;}/** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1));}/** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */function baseRange(start,end,step,fromRight){var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);while(length--){result[fromRight?length:++index]=start;start+=step;}return result;}/** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */function baseRepeat(string,n){var result='';if(!string||n<1||n>MAX_SAFE_INTEGER){return result;}// Leverage the exponentiation by squaring algorithm for a faster repeat. +// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. +do{if(n%2){result+=string;}n=nativeFloor(n/2);if(n){string+=string;}}while(n);return result;}/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */function baseRest(func,start){return setToString(overRest(func,start,identity),func+'');}/** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */function baseSample(collection){return arraySample(values(collection));}/** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length));}/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */function baseSet(object,path,value,customizer){if(!isObject(object)){return object;}path=castPath(path,object);var index=-1,length=path.length,lastIndex=length-1,nested=object;while(nested!=null&&++indexlength?0:length+start;}end=end>length?length:end;if(end<0){end+=length;}length=start>end?0:end-start>>>0;start>>>=0;var result=Array(length);while(++index>>1,computed=array[mid];if(computed!==null&&!isSymbol(computed)&&(retHighest?computed<=value:computed=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set){return setToArray(set);}isCommon=false;includes=cacheHas;seen=new SetCache();}else{seen=iteratee?[]:result;}outer:while(++index=length?array:baseSlice(array,start,end);}/** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */var clearTimeout=ctxClearTimeout||function(id){return root.clearTimeout(id);};/** + * Creates a clone of `buffer`. * - * // Returns a wrapped value. - * var squares = wrapped.map(square); + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */function cloneBuffer(buffer,isDeep){if(isDeep){return buffer.slice();}var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);buffer.copy(result);return result;}/** + * Creates a clone of `arrayBuffer`. * - * _.isArray(squares); - * // => false + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);new Uint8Array(result).set(new Uint8Array(arrayBuffer));return result;}/** + * Creates a clone of `dataView`. * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength);}/** + * Creates a clone of `map`. * * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * The function whose prototype chain sequence wrappers inherit from. + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. + */function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),CLONE_DEEP_FLAG):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor());}/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));result.lastIndex=regexp.lastIndex;return result;}/** + * Creates a clone of `set`. + * + * @private + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),CLONE_DEEP_FLAG):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor());}/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{};}/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length);}/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=value===null,valIsReflexive=value===value,valIsSymbol=isSymbol(value);var othIsDefined=other!==undefined,othIsNull=other===null,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive){return 1;}if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value=ordersLength){return result;}var order=orders[index];return result*(order=='desc'?-1:1);}}// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications +// that causes it, under certain circumstances, to provide the same value for +// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 +// for more details. +// +// This also ensures a stable sort in V8 and other engines. +// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. +return object.index-other.index;}/** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */function composeArgs(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;while(++leftIndex1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;customizer=assigner.length>3&&typeof customizer=='function'?(length--,customizer):undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined:customizer;length=1;}object=Object(object);while(++index-1?iterable[iteratee?collection[index]:index]:undefined;};}/** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;if(fromRight){funcs.reverse();}while(index--){var func=funcs[index];if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(prereq&&!wrapper&&getFuncName(func)=='wrapper'){var wrapper=new LodashWrapper([],true);}}index=wrapper?index:length;while(++index1){args.reverse();}if(isAry&&aryarrLength)){return false;}// Assume cyclic values are equal. +var stacked=stack.get(array);if(stacked&&stack.get(other)){return stacked==other;}var index=-1,result=true,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache():undefined;stack.set(array,other);stack.set(other,array);// Ignore non-index properties. +while(++index -1; - } - - /** - * Sets the list cache `key` to `value`. + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */function getView(start,end,transforms){var index=-1,length=transforms.length;while(++index1?'& ':'')+details[lastIndex];details=details.join(length>2?', ':' ');return source.replace(reWrapComment,'{\n/* [wrapped with '+details+'] */\n');}/** + * Checks if `value` is a flattenable `arguments` object or array. * * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /*------------------------------------------------------------------------*/ - - /** + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol]);}/** + * Checks if `value` is a valid array-like index. * - * Creates an array cache object to store unique values. + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */function isIndex(value,length){length=length==null?MAX_SAFE_INTEGER:length;return!!length&&(typeof value=='number'||reIsUint.test(value))&&value>-1&&value%1==0&&value0){if(++count>=HOT_COUNT){return arguments[0];}}else{count=0;}return func.apply(undefined,arguments);};}/** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;size=size===undefined?length:size;while(++index [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */function chunk(array,size,guard){if(guard?isIterateeCall(array,size,guard):size===undefined){size=1;}else{size=nativeMax(toInteger(size),0);}var length=array==null?0:array.length;if(!length||size<1){return[];}var index=0,resIndex=0,result=Array(nativeCeil(length/size));while(index [1, 2, 3] + */function compact(array){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */function concat(){var length=arguments.length;if(!length){return[];}var args=Array(length-1),array=arguments[0],index=length;while(index--){args[index-1]=arguments[index];}return arrayPush(isArray(array)?copyArray(array):[array],baseFlatten(args,1));}/** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */var difference=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true)):[];});/** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */var differenceBy=baseRest(function(array,values){var iteratee=last(values);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),getIteratee(iteratee,2)):[];});/** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */var differenceWith=baseRest(function(array,values){var comparator=last(values);if(isArrayLikeObject(comparator)){comparator=undefined;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),undefined,comparator):[];});/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */function drop(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,n<0?0:n,length);}/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */function dropRight(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,0,n<0?0:n);}/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true,true):[];}/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); - - /** - * The base implementation of `_.every` without support for iteratee shorthands. + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } - - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index], - current = iteratee(value); - - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } - - /** - * The base implementation of `_.fill` without an iteratee call guard. + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] * - * @private + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true):[];}/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; - - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; - } - - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } - - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * @example * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } - - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. + * var array = [1, 2, 3]; * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } - - /** - * The base implementation of `_.get` without support for default values. + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. + * _.fill(Array(3), 2); + * // => [2, 2, 2] * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */function fill(array,value,start,end){var length=array==null?0:array.length;if(!length){return[];}if(start&&typeof start!='number'&&isIterateeCall(array,value,start)){start=0;end=length;}return baseFill(array,value,start,end);}/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * The base implementation of `_.gt` which doesn't coerce arguments. + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } - - /** - * The base implementation of `_.has` without support for deep paths. + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } - - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; - - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; - - var index = -1, - seen = caches[0]; - - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */function findIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseFindIndex(array,getIteratee(predicate,3),index);}/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } - - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } - - /** - * The base implementation of `_.isArguments`. + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } - - /** - * The base implementation of `_.isDate` without Node.js optimizations. + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */function findLastIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=length-1;if(fromIndex!==undefined){index=toInteger(fromIndex);index=fromIndex<0?nativeMax(length+index,0):nativeMin(index,length-1);}return baseFindIndex(array,getIteratee(predicate,3),index,true);}/** + * Flattens `array` a single level deep. * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); - - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isMap` without Node.js optimizations. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */function flatten(array){var length=array==null?0:array.length;return length?baseFlatten(array,1):[];}/** + * Recursively flattens `array`. * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * The base implementation of `_.isNative` without bad shim checks. + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */function flattenDeep(array){var length=array==null?0:array.length;return length?baseFlatten(array,INFINITY):[];}/** + * Recursively flatten `array` up to `depth` times. * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - - /** - * The base implementation of `_.isSet` without Node.js optimizations. + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. + * var array = [1, [2, [3, [4]], 5]]; * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.iteratee`. + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */function flattenDepth(array,depth){var length=array==null?0:array.length;if(!length){return[];}depth=depth===undefined?1:toInteger(depth);return baseFlatten(array,depth);}/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.lt` which doesn't coerce arguments. + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */function fromPairs(pairs){var index=-1,length=pairs==null?0:pairs.length,result={};while(++index 1 * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * _.head([]); + * // => undefined + */function head(array){return array&&array.length?array[0]:undefined;}/** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } - - /** - * The base implementation of `_.merge` without support for multiple sources. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - if (isObject(srcValue)) { - stack || (stack = new Stack); - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(object[key], srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = object[key], - srcValue = source[key], - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.nth` which doesn't coerce arguments. + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */function indexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseIndexOf(array,value,index);}/** + * Gets all but the last element of `array`. * - * @private + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; - } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; - } - - /** - * The base implementation of `_.orderBy` without param guards. + * @returns {Array} Returns the slice of `array`. + * @example * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseOrderBy(collection, iteratees, orders) { - var index = -1; - iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); - - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. + * _.initial([1, 2, 3]); + * // => [1, 2] + */function initial(array){var length=array==null?0:array.length;return length?baseSlice(array,0,-1):[];}/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. + * _.intersection([2, 1], [2, 3]); + * // => [2] + */var intersection=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[];});/** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */var intersectionBy=baseRest(function(arrays){var iteratee=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);if(iteratee===last(mapped)){iteratee=undefined;}else{mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,getIteratee(iteratee,2)):[];});/** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; - - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); - } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; - - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } - - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. + * @returns {Array} Returns the new array of intersecting values. + * @example * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; - - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } - - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */var intersectionWith=baseRest(function(arrays){var comparator=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);comparator=typeof comparator=='function'?comparator:undefined;if(comparator){mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,undefined,comparator):[];});/** + * Converts all elements in `array` into a string separated by `separator`. * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } - - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); - - return result; - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */function join(array,separator){return array==null?'':nativeJoin.call(array,separator);}/** + * Gets the last element of `array`. * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * The base implementation of `_.sample`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } - - /** - * The base implementation of `_.sampleSize` without param guards. + * _.last([1, 2, 3]); + * // => 3 + */function last(array){var length=array==null?0:array.length;return length?array[length-1]:undefined;}/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } - - /** - * The base implementation of `_.set`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `setData` without support for hot loop shorting. + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - - /** - * The base implementation of `setToString` without support for hot loop shorting. + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */function lastIndexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=length;if(fromIndex!==undefined){index=toInteger(fromIndex);index=index<0?nativeMax(length+index,0):nativeMin(index,length-1);}return value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,true);}/** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** - * The base implementation of `_.shuffle`. + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. + * var array = ['a', 'b', 'c', 'd']; * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * The base implementation of `_.some` without support for iteratee shorthands. + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined;}/** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } - - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } - - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - value = iteratee(value); - - var low = 0, - high = array == null ? 0 : array.length, - valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); - - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } - - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */var pull=baseRest(pullAll);/** + * This method is like `_.pull` except that it accepts an array of values to remove. * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. + * **Note:** Unlike `_.difference`, this method mutates `array`. * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.unset`. + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } - - /** - * The base implementation of `_.update`. + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array;}/** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } - - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} - - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } - - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } - - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); - - while (++index < length) { - var array = arrays[index], - othIndex = -1; - - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } - - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array;}/** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; - - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } - - /** - * Casts `value` to an empty array if it's not an array like object. + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } - - /** - * Casts `value` to `identity` if it's not a function. + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } - - /** - * Casts `value` to a path array if it's not one. + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array;}/** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - var castRest = baseRest; - - /** - * Casts `array` to a slice if it's needed. + * **Note:** Unlike `_.at`, this method mutates `array`. * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } - - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; - - /** - * Creates a clone of `buffer`. + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. + * console.log(array); + * // => ['a', 'c'] * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. + * console.log(pulled); + * // => ['b', 'd'] + */var pullAt=flatRest(function(array,indexes){var length=array==null?0:array.length,result=baseAt(array,indexes);basePullAt(array,arrayMap(indexes,function(index){return isIndex(index,length)?+index:index;}).sort(compareAscending));return result;});/** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `map`. + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); - } - - /** - * Creates a clone of `regexp`. + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of `set`. + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } - - /** - * Creates a clone of the `symbol` object. + * console.log(array); + * // => [1, 3] * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. + * console.log(evens); + * // => [2, 4] + */function remove(array,predicate){var result=[];if(!(array&&array.length)){return result;}var index=-1,indexes=[],length=array.length;predicate=getIteratee(predicate,3);while(++index other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } - - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. + * var array = [1, 2, 3]; * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; - - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } - - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. + * _.reverse(array); + * // => [3, 2, 1] * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } - - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. + * console.log(array); + * // => [3, 2, 1] + */function reverse(array){return array==null?array:nativeReverse.call(array);}/** + * Creates a slice of `array` from `start` up to, but not including, `end`. * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; - - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result; - } - - /** - * Copies the values of `source` to `array`. + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */function slice(array,start,end){var length=array==null?0:array.length;if(!length){return[];}if(end&&typeof end!='number'&&isIterateeCall(array,start,end)){start=0;end=length;}else{start=start==null?0:toInteger(start);end=end===undefined?length:toInteger(end);}return baseSlice(array,start,end);}/** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * Copies own symbols of `source` to `object`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Copies own and inherited symbols of `source` to `object`. + * _.sortedIndex([30, 50], 40); + * // => 1 + */function sortedIndex(array,value){return baseSortedIndex(array,value);}/** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } - - /** - * Creates a function like `_.groupBy`. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; - - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } - - /** - * Creates a function like `_.assign`. + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * Creates a `baseEach` or `baseEachRight` function. + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */function sortedIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2));}/** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - - /** - * Creates a function like `_.lowerFirst`. + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */function sortedIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value);if(index 4 + */function sortedLastIndex(array,value){return baseSortedIndex(array,value,true);}/** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } - - /** - * Creates a function that wraps `func` to enable currying. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); - - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); - - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; - } - - /** - * Creates a `_.find` or `_.findLast` function. + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } - - /** - * Creates a `_.flow` or `_.flowRight` function. + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; - - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; - - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; - - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; - - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } - - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),true);}/** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; - - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; - - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); - } - return wrapper; - } - - /** - * Creates a function like `_.invertBy`. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; - } - - /** - * Creates a function that performs a mathematical operation on two values. + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */function sortedLastIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value,true)-1;if(eq(array[index],value)){return index;}}return-1;}/** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; - } - if (other !== undefined) { - if (result === undefined) { - return other; - } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result = operator(value, other); - } - return result; - }; - } - - /** - * Creates a function like `_.over`. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); - } - - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[];}/** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); - - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); - } - - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); - } - return wrapper; - } - - /** - * Creates a `_.range` or `_.rangeRight` function. + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[];}/** + * Gets all but the first element of `array`. * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } - - /** - * Creates a function that performs a relational operation on two values. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; - } - - /** - * Creates a function that wraps `func` to continue currying. + * _.tail([1, 2, 3]); + * // => [2, 3] + */function tail(array){var length=array==null?0:array.length;return length?baseSlice(array,1,length):[];}/** + * Creates a slice of `array` with `n` elements taken from the beginning. * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; - - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; - - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } - - /** - * Creates a function like `_.round`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); - - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; - } - - /** - * Creates a set object of `values`. + * _.take([1, 2, 3]); + * // => [1] * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; - - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. + * _.take([1, 2, 3], 2); + * // => [1, 2] * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } - - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); - - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; - - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); - - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); - } - - /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. + * _.take([1, 2, 3], 0); + * // => [] + */function take(array,n,guard){if(!(array&&array.length)){return[];}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,0,n<0?0:n);}/** + * Creates a slice of `array` with `n` elements taken from the end. * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; - } - - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); - } - return objValue; - } - - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. + * _.takeRight([1, 2, 3]); + * // => [3] * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; - } - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * _.takeRight([1, 2, 3], 0); + * // => [] + */function takeRight(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,n<0?0:n,length);}/** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag: - return object.name == other.name && object.message == other.message; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag: - var convert = mapToArray; - - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseRest` which flattens the rest array. + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Gets metadata for `func`. + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - - /** - * Gets the name of `func`. + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),false,true):[];}/** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } - - /** - * Gets the argument placeholder value for `func`. + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example * - * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. - */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; - } - - /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. - */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; - } - - /** - * Gets the data for `map`. + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the property names, values, and compare flags of `object`. + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * Gets the native function at `key` of `object`. + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[];}/** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - - /** - * Creates an array of the own enumerable symbols of `object`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. + * _.union([2], [1, 2]); + * // => [2, 1] + */var union=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true));});/** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Gets the `toStringTag` of `value`. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; - - while (++index < length) { - var data = transforms[index], - size = data.size; - - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } - - /** - * Extracts wrapper details from the `source` body comment. + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */var unionBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),getIteratee(iteratee,2));});/** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). * - * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. - */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } - - /** - * Checks if `path` exists on `object`. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Initializes an array clone. + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */var unionWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined;return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),undefined,comparator);});/** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * _.uniq([2, 1, 2]); + * // => [2, 1] + */function uniq(array){return array&&array.length?baseUniq(array):[];}/** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[];}/** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). * - * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. - */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); - } - - /** - * Checks if `value` is a flattenable `arguments` object or array. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); - } - - /** - * Checks if `value` is a valid array-like index. + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if the given arguments are from an iteratee call. + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */function uniqWith(array,comparator){comparator=typeof comparator=='function'?comparator:undefined;return array&&array.length?baseUniq(array,undefined,comparator):[];}/** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Checks if `value` is a property name and not a property path. + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** - * Checks if `value` is suitable for use as unique object key. + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has a lazy counterpart. + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */function unzip(array){if(!(array&&array.length)){return[];}var length=0;array=arrayFilter(array,function(group){if(isArrayLikeObject(group)){length=nativeMax(group.length,length);return true;}});return baseTimes(length,function(index){return arrayMap(array,baseProperty(index));});}/** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. - */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; - - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } - - /** - * Checks if `func` has its source masked. + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `func` is capable of being masked. + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ - var isMaskable = coreJsData ? isFunction : stubFalse; - - /** - * Checks if `value` is likely a prototype object. + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */function unzipWith(array,iteratee){if(!(array&&array.length)){return[];}var result=unzip(array);if(iteratee==null){return result;}return arrayMap(result,function(group){return apply(iteratee,undefined,group);});}/** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * **Note:** Unlike `_.pull`, this method returns a new array. * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */var without=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[];});/** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** - * Merges the function metadata of `source` into `data`. + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */var xor=baseRest(function(arrays){return baseXor(arrayFilter(arrays,isArrayLikeObject));});/** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** - * Converts `value` to a string using `Object.prototype.toString`. + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); - } - - /** - * A specialized version of `baseRest` which transforms the rest array. + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */var xorBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return baseXor(arrayFilter(arrays,isArrayLikeObject),getIteratee(iteratee,2));});/** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Gets the parent value at `path` of `object`. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. - */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } - - /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; - } - - /** - * Sets metadata for `func`. + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */var xorWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined;return baseXor(arrayFilter(arrays,isArrayLikeObject),undefined,comparator);});/** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var setData = shortOut(baseSetData); - - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */var zip=baseRest(unzip);/** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. - */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - - /** - * Sets the `toString` method of `func` to return `string`. + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue);}/** + * This method is like `_.zipObject` except that it supports property paths. * - * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. - */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet);}/** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * - * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. - */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; - - array[rand] = array[index]; - array[index] = value; - } - array.length = size; - return array; - } - - /** - * Converts `string` to a property path array. + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (reLeadingDot.test(string)) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, string) { - result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Converts `value` to a string key if it's not a string or symbol. + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */var zipWith=baseRest(function(arrays){var length=arrays.length,iteratee=length>1?arrays[length-1]:undefined;iteratee=typeof iteratee=='function'?(arrays.pop(),iteratee):undefined;return unzipWith(arrays,iteratee);});/*------------------------------------------------------------------------*//** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * Converts `func` to its source code. + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Updates wrapper `details` based on `bitmask` flags. + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; * - * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. - */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); - } - - /** - * Creates a clone of `wrapper`. + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */function chain(value){var result=lodash(value);result.__chain__=true;return result;}/** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */function tap(value,interceptor){interceptor(value);return value;}/** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. * @example * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */function thru(value,interceptor){return interceptor(value);}/** + * This method is the wrapper version of `_.at`. * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; - } - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example * - * @static + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */var wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function interceptor(object){return baseAt(object,paths);};if(length>1||this.__actions__.length||!(value instanceof LazyWrapper)||!isIndex(start)){return this.thru(interceptor);}value=value.slice(start,+start+(length?1:0));value.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined});return new LodashWrapper(value,this.__chain__).thru(function(array){if(length&&!array.length){array.push(undefined);}return array;});});/** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain * @memberOf _ * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; * - * @static + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */function wrapperChain(){return chain(this);}/** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); + * var array = [1, 2]; + * var wrapped = _(array).push(3); * - * console.log(other); - * // => [1, 2, 3, [4]] + * console.log(array); + * // => [1, 2] * + * wrapped = wrapped.commit(); * console.log(array); - * // => [1] - */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. + * // => [1, 2, 3] * - * **Note:** Unlike `_.pullAll`, this method returns a new array. + * wrapped.last(); + * // => 3 * - * @static + * console.log(array); + * // => [1, 2, 3] + */function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__);}/** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. * @example * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). + * var wrapped = _([1, 2]); * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * wrapped.next(); + * // => { 'done': false, 'value': 1 } * - * @static + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */function wrapperNext(){if(this.__values__===undefined){this.__values__=toArray(this.value());}var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{'done':done,'value':value};}/** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator * @memberOf _ * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. + * @category Seq + * @returns {Object} Returns the wrapper object. * @example * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] + * var wrapped = _([1, 2]); * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). + * wrapped[Symbol.iterator]() === wrapped; + * // => true * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * Array.from(wrapped); + * // => [1, 2] + */function wrapperToIterator(){return this;}/** + * Creates a clone of the chain sequence planting `value` as the wrapped value. * - * @static + * @name plant * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * function square(n) { + * return n * n; + * } * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); - - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); * - * @static + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */function wrapperPlant(value){var result,parent=this;while(parent instanceof baseLodash){var clone=wrapperClone(parent);clone.__index__=0;clone.__values__=undefined;if(result){previous.__wrapped__=clone;}else{result=clone;}var previous=clone;parent=parent.__wrapped__;}previous.__wrapped__=value;return result;}/** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.drop([1, 2, 3]); - * // => [2, 3] + * var array = [1, 2, 3]; * - * _.drop([1, 2, 3], 2); - * // => [3] + * _(array).reverse().value() + * // => [3, 2, 1] * - * _.drop([1, 2, 3], 5); - * // => [] + * console.log(array); + * // => [3, 2, 1] + */function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;if(this.__actions__.length){wrapped=new LazyWrapper(this);}wrapped=wrapped.reverse();wrapped.__actions__.push({'func':thru,'args':[reverse],'thisArg':undefined});return new LodashWrapper(wrapped,this.__chain__);}return this.thru(reverse);}/** + * Executes the chain sequence to resolve the unwrapped value. * - * _.drop([1, 2, 3], 0); + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); * // => [1, 2, 3] - */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with `n` elements dropped from the end. + */function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__);}/*------------------------------------------------------------------------*//** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). * * @static * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. * @example * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } * - * _.dropRight([1, 2, 3], 5); - * // => [] + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */var countBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){++result[key];}else{baseAssignValue(result,key,1);}});/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. * * @static * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. * @example * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } * ]; * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false * * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] + * _.every(users, ['active', false]); + * // => true * * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; - } - - /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). + * _.every(users, 'active'); + * // => false + */function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}return func(collection,getIteratee(predicate,3));}/** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. + * @returns {Array} Returns the new filtered array. + * @see _.reject * @example * * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } * ]; * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] + * _.filter(users, ['active', false]); + * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; - } - - /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] - * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] - */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; - } - return baseFill(array, value, start, end); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3));}/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). * * @static * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. + * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' * * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 + * _.find(users, ['active', false]); + * // => object for 'fred' * * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); - } - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. + * _.find(users, 'active'); + * // => object for 'barney' + */var find=createFind(findIndex);/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 - */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } - - /** - * Flattens `array` a single level deep. + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */var findLast=createFind(findLastIndex);/** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). * * @static * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - - /** - * Recursively flattens `array`. + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1);}/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. * * @static * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - - /** - * Recursively flatten `array` up to `depth` times. + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY);}/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. * * @static * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * - * var array = [1, [2, [3, [4]], 5]]; + * function duplicate(n) { + * return [[[n, n]]]; + * } * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */function flatMapDepth(collection,iteratee,depth){depth=depth===undefined?1:toInteger(depth);return baseFlatten(map(collection,iteratee),depth);}/** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } - - /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight * @example * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; - - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; - } - return result; - } - - /** - * Gets the first element of `array`. + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3));}/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. * * @static * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach * @example * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } - - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3));}/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. * @example * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value, index); - } - - /** - * Gets all but the last element of `array`. + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value);}else{baseAssignValue(result,key,[value]);}});/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } - - /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection);fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0);}return isString(collection)?fromIndex<=length&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1;}/** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. * @example * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */var invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc=typeof path=='function',result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value){result[++index]=isFunc?apply(path,value,args):baseInvoke(value,path,args);});return result;});/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. * @example * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */var keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value);});/** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. * @example * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * function square(n) { + * return n * n; + * } * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); - - /** - * Converts all elements in `array` into a string separated by `separator`. + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3));}/** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. * @example * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); - } - - /** - * Gets the last element of `array`. + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */function orderBy(collection,iteratees,orders,guard){if(collection==null){return[];}if(!isArray(iteratees)){iteratees=iteratees==null?[]:[iteratees];}orders=guard?undefined:orders;if(!isArray(orders)){orders=orders==null?[]:[orders];}return baseOrderBy(collection,iteratees,orders);}/** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). * * @static * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. * @example * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } - - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */var partition=createAggregator(function(result,value,key){result[key?0:1].push(value);},function(){return[[],[]];});/** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight * @example * - * _.lastIndexOf([1, 2, 1, 2], 2); + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); * // => 3 * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 - */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); - } - - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach);}/** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. * * @static * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce * @example * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' - * - * _.nth(array, -2); - * // => 'c'; - */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; - } - - /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. + * var array = [[0, 1], [2, 3], [4, 5]]; * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight);}/** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. * * @static * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter * @example * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); - - /** - * This method is like `_.pull` except that it accepts an array of values to remove. + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] * - * **Note:** Unlike `_.difference`, this method mutates `array`. + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)));}/** + * Gets a random element from `collection`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. * @example * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * _.sample([1, 2, 3, 4]); + * // => 2 + */function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection);}/** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. * @example * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */function sampleSize(collection,n,guard){if(guard?isIterateeCall(collection,n,guard):n===undefined){n=1;}else{n=toInteger(n);}var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n);}/** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. * @example * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] - */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; - } - - /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection);}/** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. * @example * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] + * _.size([1, 2, 3]); + * // => 3 * - * console.log(pulled); - * // => ['b', 'd'] - */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); - - /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. + * _.size('pebbles'); + * // => 7 + */function size(collection){if(collection==null){return 0;}if(isArrayLike(collection)){return isString(collection)?stringSize(collection):collection.length;}var tag=getTag(collection);if(tag==mapTag||tag==setTag){return collection.size;}return baseKeys(collection).length;}/** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. * @example * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); + * _.some([null, 0, 'yes', false], Boolean); + * // => true * - * console.log(array); - * // => [1, 3] + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; - - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result; - } - - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}return func(collection,getIteratee(predicate,3));}/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. * @example * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); - } - return baseSlice(array, start, end); - } - - /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */var sortBy=baseRest(function(collection,iteratees){if(collection==null){return[];}var length=iteratees.length;if(length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])){iteratees=[];}else if(length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])){iteratees=[iteratees[0]];}return baseOrderBy(collection,baseFlatten(iteratees,1),[]);});/*------------------------------------------------------------------------*//** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. * @example * - * _.sortedIndex([30, 50], 40); - * // => 1 - */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); - } - - /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */var now=ctxNow||function(){return root.Date.now();};/*------------------------------------------------------------------------*//** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. * @example * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * var saves = ['profile', 'settings']; * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 - */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); - } - - /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */function after(n,func){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n<1){return func.apply(this,arguments);}};}/** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. * @example * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */function ary(func,n,guard){n=guard?undefined:n;n=func&&n==null?func.length:n;return createWrap(func,WRAP_ARY_FLAG,undefined,undefined,undefined,undefined,n);}/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. * @example * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 - */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); - } - - /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */function before(n,func){var result;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n>0){result=func.apply(this,arguments);}if(n<=1){func=undefined;}return result;};}/** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. * @example * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 + * var object = { 'user': 'fred' }; * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 - */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); - } - - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */var bind=baseRest(function(func,thisArg,partials){var bitmask=WRAP_BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(func,bitmask,thisArg,partials,holders);});/** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. * @example * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } - - /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; - } - - /** - * Gets all but the first element of `array`. + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * bound('!'); + * // => 'hiya fred!' * - * _.tail([1, 2, 3]); - * // => [2, 3] - */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - - /** - * Creates a slice of `array` with `n` elements taken from the beginning. + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */var bindKey=baseRest(function(object,key,partials){var bitmask=WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(key,bitmask,object,partials,holders);});/** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. + * @returns {Function} Returns the new curried function. * @example * - * _.take([1, 2, 3]); - * // => [1] + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); * - * _.take([1, 2, 3], 2); - * // => [1, 2] + * curried(1)(2)(3); + * // => [1, 2, 3] * - * _.take([1, 2, 3], 5); + * curried(1, 2)(3); * // => [1, 2, 3] * - * _.take([1, 2, 3], 0); - * // => [] - */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with `n` elements taken from the end. + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curry.placeholder;return result;}/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. + * @returns {Function} Returns the new curried function. * @example * - * _.takeRight([1, 2, 3]); - * // => [3] + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] + * var curried = _.curryRight(abc); * - * _.takeRight([1, 2, 3], 5); + * curried(3)(2)(1); * // => [1, 2, 3] * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example + * curried(2, 3)(1); + * // => [1, 2, 3] * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; + * curried(1, 2, 3); + * // => [1, 2, 3] * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curryRight.placeholder;return result;}/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] - */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; - } - - /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. * @example * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] - */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; - } - - /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */function debounce(func,wait,options){var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=false,maxing=false,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}wait=toNumber(wait)||0;if(isObject(options)){leading=!!options.leading;maxing='maxWait'in options;maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait;trailing='trailing'in options?!!options.trailing:trailing;}function invokeFunc(time){var args=lastArgs,thisArg=lastThis;lastArgs=lastThis=undefined;lastInvokeTime=time;result=func.apply(thisArg,args);return result;}function leadingEdge(time){// Reset any `maxWait` timer. +lastInvokeTime=time;// Start the timer for the trailing edge. +timerId=setTimeout(timerExpired,wait);// Invoke the leading edge. +return leading?invokeFunc(time):result;}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result;}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;// Either this is the first call, activity has stopped and we're at the +// trailing edge, the system time has gone backwards and we're treating +// it as the trailing edge, or we've hit the `maxWait` limit. +return lastCallTime===undefined||timeSinceLastCall>=wait||timeSinceLastCall<0||maxing&&timeSinceLastInvoke>=maxWait;}function timerExpired(){var time=now();if(shouldInvoke(time)){return trailingEdge(time);}// Restart the timer. +timerId=setTimeout(timerExpired,remainingWait(time));}function trailingEdge(time){timerId=undefined;// Only invoke if we have `lastArgs` which means `func` has been +// debounced at least once. +if(trailing&&lastArgs){return invokeFunc(time);}lastArgs=lastThis=undefined;return result;}function cancel(){if(timerId!==undefined){clearTimeout(timerId);}lastInvokeTime=0;lastArgs=lastCallTime=lastThis=timerId=undefined;}function flush(){return timerId===undefined?result:trailingEdge(now());}function debounced(){var time=now(),isInvoking=shouldInvoke(time);lastArgs=arguments;lastThis=this;lastCallTime=time;if(isInvoking){if(timerId===undefined){return leadingEdge(lastCallTime);}if(maxing){// Handle invocations in a tight loop. +timerId=setTimeout(timerExpired,wait);return invokeFunc(lastCallTime);}}if(timerId===undefined){timerId=setTimeout(timerExpired,wait);}return result;}debounced.cancel=cancel;debounced.flush=flush;return debounced;}/** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. * @example * - * _.union([2], [1, 2]); - * // => [2, 1] - */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - - /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */var defer=baseRest(function(func,args){return baseDelay(func,1,args);});/** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. * @example * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */var delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args);});/** + * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. * @example * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); - - /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */function flip(func){return createWrap(func,WRAP_FLIP_FLAG);}/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. * @example * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] + * values(other); + * // => [3, 4] * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */function memoize(func,resolver){if(typeof func!='function'||resolver!=null&&typeof resolver!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var memoized=function memoized(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key);}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result;};memoized.cache=new(memoize.Cache||MapCache)();return memoized;}// Expose `MapCache`. +memoize.Cache=MapCache;/** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. * @example * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * function isEven(n) { + * return n % 2 == 0; + * } * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; - } - - /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */function negate(predicate){if(typeof predicate!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2]);}return!predicate.apply(this,args);};}/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. * @example * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); - } - - /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */function once(func){return before(2,func);}/** + * Creates a function that invokes `func` with its arguments transformed. * * @static + * @since 4.0.0 * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. * @example * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] + * function doubled(n) { + * return n * 2; + * } * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; - } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); - } - - /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. + * function square(n) { + * return n * n; + * } * - * **Note:** Unlike `_.pull`, this method returns a new array. + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example + * func(9, 3); + * // => [81, 6] * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] - */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); - - /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. + * func(10, 5); + * // => [100, 10] + */var overArgs=castRest(function(func,transforms){transforms=transforms.length==1&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){var index=-1,length=nativeMin(args.length,funcsLength);while(++index [1, 3] - */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - - /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). + * **Note:** This method doesn't set the "length" property of partially + * applied functions. * * @static * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. * @example * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */var partial=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partial));return createWrap(func,WRAP_PARTIAL_FLAG,undefined,partials,holders);});/** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); - - /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. + * **Note:** This method doesn't set the "length" property of partially + * applied functions. * * @static * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. * @example * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ - var zip = baseRest(unzip); - - /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); - } - - /** - * This method is like `_.zipObject` except that it supports property paths. + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */var partialRight=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partialRight));return createWrap(func,WRAP_PARTIAL_RIGHT_FLAG,undefined,partials,holders);});/** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. * * @static * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. * @example * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } - */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); - } - - /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */var rearg=flatRest(function(func,indexes){return createWrap(func,WRAP_REARG_FLAG,undefined,undefined,undefined,indexes);});/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. * @example * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); - * // => [111, 222] - */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; - - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */function rest(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start===undefined?start:toInteger(start);return baseRest(func,start);}/** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. * @example * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; - } - - /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */function spread(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start==null?0:nativeMax(toInteger(start),0);return baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);if(array){arrayPush(otherArgs,array);}return apply(func,this,otherArgs);});}/** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. * @example * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor) { - interceptor(value); - return value; - } - - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor) { - return interceptor(value); - } - - /** - * This method is the wrapper version of `_.at`. + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */function throttle(func,wait,options){var leading=true,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(isObject(options)){leading='leading'in options?!!options.leading:leading;trailing='trailing'in options?!!options.trailing:trailing;}return debounce(func,wait,{'leading':leading,'maxWait':wait,'trailing':trailing});}/** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. * - * @name at + * @static * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] - */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; - - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); - } - return array; - }); - }); - - /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */function unary(func){return ary(func,1);}/** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. * - * @name chain + * @static * @memberOf _ * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. * @example * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - - /** - * Executes the chain sequence and returns the wrapped result. + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */function wrap(value,wrapper){return partial(castFunction(wrapper),value);}/*------------------------------------------------------------------------*//** + * Casts `value` as an array if it's not one. * - * @name commit + * @static * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. * @example * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] + * _.castArray(1); + * // => [1] * - * wrapped.last(); - * // => 3 + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] * - * console.log(array); - * // => [1, 2, 3] - */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - - /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * _.castArray('abc'); + * // => ['abc'] * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example + * _.castArray(null); + * // => [null] * - * var wrapped = _([1, 2]); + * _.castArray(undefined); + * // => [undefined] * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } + * _.castArray(); + * // => [] * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */function castArray(){if(!arguments.length){return[];}var value=arguments[0];return isArray(value)?value:[value];}/** + * Creates a shallow clone of `value`. * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } - */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; - - return { 'done': done, 'value': value }; - } - - /** - * Enables the wrapper to be iterable. + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. * - * @name Symbol.iterator + * @static * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep * @example * - * var wrapped = _([1, 2]); + * var objects = [{ 'a': 1 }, { 'b': 2 }]; * - * wrapped[Symbol.iterator]() === wrapped; + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); * // => true + */function clone(value){return baseClone(value,CLONE_SYMBOLS_FLAG);}/** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). * - * Array.from(wrapped); - * // => [1, 2] - */ - function wrapperToIterator() { - return this; - } - - /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant + * @static * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith * @example * - * function square(n) { - * return n * n; + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } * } * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ - function wrapperPlant(value) { - var result, - parent = this; - - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; - } - previous.__wrapped__ = value; - return result; - } - - /** - * This method is the wrapper version of `_.reverse`. + * var el = _.cloneWith(document.body, customizer); * - * **Note:** This method mutates the wrapped array. + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */function cloneWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseClone(value,CLONE_SYMBOLS_FLAG,customizer);}/** + * This method is like `_.clone` except that it recursively clones `value`. * - * @name reverse + * @static * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone * @example * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] + * var objects = [{ 'a': 1 }, { 'b': 2 }]; * - * console.log(array); - * // => [3, 2, 1] - */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - - /** - * Executes the chain sequence to resolve the unwrapped value. + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */function cloneDeep(value){return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG);}/** + * This method is like `_.cloneWith` except that it recursively clones `value`. * - * @name value + * @static * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith * @example * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */function cloneDeepWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG,customizer);}/** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. * * @static * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } + * var object = { 'a': 1, 'b': 2 }; * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); - } - }); - - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */function conformsTo(object,source){return source==null||baseConformsTo(object,source,keys(source));}/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; + * _.eq(object, object); + * // => true * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); + * _.eq(object, other); * // => false * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); + * _.eq('a', 'a'); * // => true * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); + * _.eq('a', Object('a')); * // => false - */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). * - * **Note:** Unlike `_.remove`, this method returns a new array. + * _.eq(NaN, NaN); + * // => true + */function eq(value,other){return value===other||value!==value&&other!==other;}/** + * Checks if `value` is greater than `other`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt * @example * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; + * _.gt(3, 1); + * // => true * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] + * _.gt(3, 3); + * // => false * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] + * _.gt(1, 3); + * // => false + */var gt=createRelationalOperation(baseGt);/** + * Checks if `value` is greater than or equal to `other`. * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */var gte=createRelationalOperation(function(value,other){return value>=other;});/** + * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. * @example * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; + * _.isArguments(function() { return arguments; }()); + * // => true * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' + * _.isArguments([1, 2, 3]); + * // => false + */var isArguments=baseIsArguments(function(){return arguments;}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee');};/** + * Checks if `value` is classified as an `Array` object. * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' + * _.isArray([1, 2, 3]); + * // => true * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); - - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */var isArray=Array.isArray;/** + * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ - var findLast = createFind(findLastIndex); - - /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */var isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer;/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * - * function duplicate(n) { - * return [n, n]; - * } + * _.isArrayLike([1, 2, 3]); + * // => true * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value);}/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. * * @static * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. * @example * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * _.isArrayLikeObject([1, 2, 3]); + * // => true * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value);}/** + * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] - */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); - } - - /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. + * _.isBoolean(false); + * // => true * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. + * _.isBoolean(null); + * // => false + */function isBoolean(value){return value===true||value===false||isObjectLike(value)&&baseGetTag(value)==boolTag;}/** + * Checks if `value` is a buffer. * * @static * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. + * _.isBuffer(new Buffer(2)); + * // => true * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. + * _.isBuffer(new Uint8Array(2)); + * // => false + */var isBuffer=nativeIsBuffer||stubFalse;/** + * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. - */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */var isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate;/** + * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } + * _.isElement(document.body); + * // => true * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } - }); - - /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. + * _.isElement(''); + * // => false + */function isElement(value){return isObjectLike(value)&&value.nodeType===1&&!isPlainObject(value);}/** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * - * _.includes([1, 2, 3], 1); + * _.isEmpty(null); * // => true * - * _.includes([1, 2, 3], 1, 2); - * // => false + * _.isEmpty(true); + * // => true * - * _.includes({ 'a': 1, 'b': 2 }, 1); + * _.isEmpty(1); * // => true * - * _.includes('abcd', 'bc'); + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */function isEmpty(value){if(value==null){return true;}if(isArrayLike(value)&&(isArray(value)||typeof value=='string'||typeof value.splice=='function'||isBuffer(value)||isTypedArray(value)||isArguments(value))){return!value.length;}var tag=getTag(value);if(tag==mapTag||tag==setTag){return!value.size;}if(isPrototype(value)){return!baseKeys(value).length;}for(var key in value){if(hasOwnProperty.call(value,key)){return false;}}return true;}/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); * // => true - */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); - } - - /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. + * + * object === other; + * // => false + */function isEqual(value,other){return baseIsEqual(value,other);}/** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */function isEqualWith(value,other,customizer){customizer=typeof customizer=='function'?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,undefined,customizer):!!result;}/** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] + * _.isError(new Error); + * // => true * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result; - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). + * _.isError(Error); + * // => false + */function isError(value){if(!isObjectLike(value)){return false;}var tag=baseGetTag(value);return tag==errorTag||tag==domExcTag||typeof value.message=='string'&&typeof value.name=='string'&&!isPlainObject(value);}/** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * _.isFinite(3); + * // => true * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); - - /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). + * _.isFinite(Number.MIN_VALUE); + * // => true * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * _.isFinite(Infinity); + * // => false * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * _.isFinite('3'); + * // => false + */function isFinite(value){return typeof value=='number'&&nativeIsFinite(value);}/** + * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) + * _.isFunction(_); + * // => true * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; + * _.isFunction(/abc/); + * // => false + */function isFunction(value){if(!isObject(value)){return false;}// The use of `Object#toString` avoids issues with the `typeof` operator +// in Safari 9 which returns 'object' for typed arrays and other constructors. +var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag;}/** + * Checks if `value` is an integer. * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; + * _.isInteger(3); + * // => true * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - - /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). + * _.isInteger(Number.MIN_VALUE); + * // => false * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example + * _.isInteger(Infinity); + * // => false * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; + * _.isInteger('3'); + * // => false + */function isInteger(value){return typeof value=='number'&&value==toInteger(value);}/** + * Checks if `value` is a valid array-like length. * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] + * _.isLength(3); + * // => true * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). + * _.isLength(Number.MIN_VALUE); + * // => false * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. + * _.isLength(Infinity); + * // => false * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` + * _.isLength('3'); + * // => false + */function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER;}/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 + * _.isObject({}); + * // => true * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); - } - - /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */function isObject(value){var type=typeof value==='undefined'?'undefined':_typeof(value);return value!=null&&(type=='object'||type=='function');}/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * - * var array = [[0, 1], [2, 3], [4, 5]]; + * _.isObjectLike({}); + * // => true * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); - } - - /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */function isObjectLike(value){return value!=null&&(typeof value==='undefined'?'undefined':_typeof(value))=='object';}/** + * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] + * _.isMap(new Map); + * // => true * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] + * _.isMap(new WeakMap); + * // => false + */var isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap;/** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } - - /** - * Gets a random element from `collection`. + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. * * @static * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * - * _.sample([1, 2, 3, 4]); - * // => 2 - */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } - - /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source));}/** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] - */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); - } - - /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. + * _.isMatchWith(object, source, customizer); + * // => true + */function isMatchWith(object,source,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseIsMatch(object,source,getMatchData(source),customizer);}/** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * - * _.size([1, 2, 3]); - * // => 3 + * _.isNaN(NaN); + * // => true * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 + * _.isNaN(new Number(NaN)); + * // => true * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */function isNaN(value){// An `NaN` primitive is the only value that is not equal to itself. +// Perform the `toStringTag` check first to avoid errors with some +// ActiveX objects in IE. +return isNumber(value)&&value!=+value;}/** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * - * _.some([null, 0, 'yes', false], Boolean); + * _.isNative(Array.prototype.push); * // => true * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); + * _.isNative(_); * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). + */function isNative(value){if(isMaskable(value)){throw new Error(CORE_ERROR_TEXT);}return baseIsNative(value);}/** + * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] - */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */function isNull(value){return value===null;}/** + * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - var now = ctxNow || function() { - return root.Date.now(); - }; - - /*------------------------------------------------------------------------*/ - - /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */function isNil(value){return value==null;}/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * - * var saves = ['profile', 'settings']; + * _.isNumber(3); + * // => true * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); + * _.isNumber(Number.MIN_VALUE); + * // => true * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. - */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */function isNumber(value){return typeof value=='number'||isObjectLike(value)&&baseGetTag(value)==numberTag;}/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); - } - - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. + * function Foo() { + * this.a = 1; + * } * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example + * _.isPlainObject(new Foo); + * // => false * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. + * _.isPlainObject([1, 2, 3]); + * // => false * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. + * _.isPlainObject(Object.create(null)); + * // => true + */function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag){return false;}var proto=getPrototype(value);if(proto===null){return true;}var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString;}/** + * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } + * _.isRegExp(/abc/); + * // => true * - * var object = { 'user': 'fred' }; + * _.isRegExp('/abc/'); + * // => false + */var isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp;/** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - - /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. + * _.isSafeInteger(3); + * // => true * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER;}/** + * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; + * _.isSet(new Set); + * // => true * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' + * _.isSet(new WeakSet); + * // => false + */var isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet;/** + * Checks if `value` is classified as a `String` primitive or object. * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example * - * bound('!'); - * // => 'hiya fred!' + * _.isString('abc'); + * // => true * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); - - /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. + * _.isString(1); + * // => false + */function isString(value){return typeof value=='string'||!isArray(value)&&isObjectLike(value)&&baseGetTag(value)==stringTag;}/** + * Checks if `value` is classified as a `Symbol` primitive or object. * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example * - * **Note:** This method doesn't set the "length" property of curried functions. + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */function isSymbol(value){return(typeof value==='undefined'?'undefined':_typeof(value))=='symbol'||isObjectLike(value)&&baseGetTag(value)==symbolTag;}/** + * Checks if `value` is classified as a typed array. * * @static * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; + * _.isTypedArray(new Uint8Array); + * // => true * - * var curried = _.curry(abc); + * _.isTypedArray([]); + * // => false + */var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;/** + * Checks if `value` is `undefined`. * - * curried(1)(2)(3); - * // => [1, 2, 3] + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example * - * curried(1, 2)(3); - * // => [1, 2, 3] + * _.isUndefined(void 0); + * // => true * - * curried(1, 2, 3); - * // => [1, 2, 3] + * _.isUndefined(null); + * // => false + */function isUndefined(value){return value===undefined;}/** + * Checks if `value` is classified as a `WeakMap` object. * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; - } - - /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. + * _.isWeakMap(new WeakMap); + * // => true * - * **Note:** This method doesn't set the "length" property of curried functions. + * _.isWeakMap(new Map); + * // => false + */function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag;}/** + * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; + * _.isWeakSet(new WeakSet); + * // => true * - * var curried = _.curryRight(abc); + * _.isWeakSet(new Set); + * // => false + */function isWeakSet(value){return isObjectLike(value)&&baseGetTag(value)==weakSetTag;}/** + * Checks if `value` is less than `other`. * - * curried(3)(2)(1); - * // => [1, 2, 3] + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example * - * curried(2, 3)(1); - * // => [1, 2, 3] + * _.lt(1, 3); + * // => true * - * curried(1, 2, 3); - * // => [1, 2, 3] + * _.lt(3, 3); + * // => false * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; - return result; - } - - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. + * _.lt(3, 1); + * // => false + */var lt=createRelationalOperation(baseLt);/** + * Checks if `value` is less than or equal to `other`. * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * _.lte(1, 3); + * // => true * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */var lte=createRelationalOperation(function(value,other){return value<=other;});/** + * Converts `value` to an array. * * @static - * @memberOf _ * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. * @example * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); + * _.toArray('abc'); + * // => ['a', 'b', 'c'] * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); + * _.toArray(1); + * // => [] * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - result = wait - timeSinceLastCall; - - return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } - - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. + * _.toArray(null); + * // => [] + */function toArray(value){if(!value){return[];}if(isArrayLike(value)){return isString(value)?stringToArray(value):copyArray(value);}if(symIterator&&value[symIterator]){return iteratorToArray(value[symIterator]());}var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value);}/** + * Converts `value` to a finite number. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. * @example * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */function toFinite(value){if(!value){return value===0?value:0;}value=toNumber(value);if(value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER;}return value===value?value:0;}/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. * @example * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - - /** - * Creates a function that invokes `func` with arguments reversed. + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0;}/** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. * @example * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); + * _.toLength(3.2); + * // => 3 * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] - */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. + * _.toLength(Number.MIN_VALUE); + * // => 0 * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0;}/** + * Converts `value` to a number. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. * @example * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] + * _.toNumber(3.2); + * // => 3.2 * - * object.a = 2; - * values(object); - * // => [1, 2] + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] + * _.toNumber(Infinity); + * // => Infinity * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. + * _.toNumber('3.2'); + * // => 3.2 + */function toNumber(value){if(typeof value=='number'){return value;}if(isSymbol(value)){return NAN;}if(isObject(value)){var other=typeof value.valueOf=='function'?value.valueOf():value;value=isObject(other)?other+'':other;}if(typeof value!='string'){return value===0?value:+value;}value=value.replace(reTrim,'');var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value;}/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. * @example * - * function isEven(n) { - * return n % 2 == 0; + * function Foo() { + * this.b = 2; * } * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */function toPlainObject(value){return copyObject(value,keysIn(value));}/** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. * @example * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ - function once(func) { - return before(2, func); - } - - /** - * Creates a function that invokes `func` with its arguments transformed. + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */function toSafeInteger(value){return value?baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER):value===0?value:0;}/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. * * @static + * @memberOf _ * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */function toString(value){return value==null?'':baseToString(value);}/*------------------------------------------------------------------------*//** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn * @example * - * function doubled(n) { - * return n * 2; + * function Foo() { + * this.a = 1; * } * - * function square(n) { - * return n * n; + * function Bar() { + * this.c = 3; * } * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] - * - * func(10, 5); - * // => [100, 10] - */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); - - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); - - /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */var assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source)){copyObject(source,keys(source),object);return;}for(var key in source){if(hasOwnProperty.call(source,key)){assignValue(object,key,source[key]);}}});/** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign * @example * - * function greet(greeting, name) { - * return greeting + ' ' + name; + * function Foo() { + * this.a = 1; * } * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' + * function Bar() { + * this.c = 3; + * } * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); - - /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */var assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object);});/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith * @example * - * function greet(greeting, name) { - * return greeting + ' ' + name; + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; * } * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * var defaults = _.partialRight(_.assignInWith, customizer); * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); - - /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */var assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer);});/** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith * @example * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); - - /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. + * var defaults = _.partialRight(_.assignWith, customizer); * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */var assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer);});/** + * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. * @example * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); - } - - /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */var at=flatRest(baseAt);/** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. * * @static * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. * @example * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' + * function Shape() { + * this.x = 0; + * this.y = 0; + * } * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); + * function Circle() { + * Shape.call(this); + * } * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); - - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); - } - - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. + * var circle = new Circle; + * circle instanceof Circle; + * // => true * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * circle instanceof Shape; + * // => true + */function create(prototype,properties){var result=baseCreate(prototype);return properties==null?result:baseAssign(result,properties);}/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. + * **Note:** This method mutates `object`. * * @static - * @memberOf _ * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); - } - - /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */var defaults=baseRest(function(args){args.push(undefined,customDefaultsAssignIn);return apply(assignInWith,undefined,args);});/** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults * @example * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ - function unary(func) { - return ary(func, 1); - } - - /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */var defaultsDeep=baseRest(function(args){args.push(undefined,customDefaultsMerge);return apply(mergeWith,undefined,args);});/** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. * @example * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' - */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Casts `value` as an array if it's not one. + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' * - * _.castArray(1); - * // => [1] + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn);}/** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. * - * _.castArray('abc'); - * // => ['abc'] + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example * - * _.castArray(null); - * // => [null] + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; * - * _.castArray(undefined); - * // => [undefined] + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * - * _.castArray(); - * // => [] + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; - } - - /** - * Creates a shallow clone of `value`. + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight);}/** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight * @example * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */function forIn(object,iteratee){return object==null?object:baseFor(object,getIteratee(iteratee,3),keysIn);}/** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn * @example * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } + * function Foo() { + * this.a = 1; + * this.b = 2; * } * - * var el = _.cloneWith(document.body, customizer); + * Foo.prototype.c = 3; * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 - */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */function forInRight(object,iteratee){return object==null?object:baseForRight(object,getIteratee(iteratee,3),keysIn);}/** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. * * @static * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight * @example * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.cloneWith` except that it recursively clones `value`. + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3));}/** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn * @example * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } + * function Foo() { + * this.a = 1; + * this.b = 2; * } * - * var el = _.cloneDeepWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 - */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. + * Foo.prototype.c = 3; * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3));}/** + * Creates an array of function property names from own enumerable properties + * of `object`. * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.14.0 - * @category Lang + * @category Object * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @returns {Array} Returns the function names. + * @see _.functionsIn * @example * - * var object = { 'a': 1, 'b': 2 }; + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true + * Foo.prototype.c = _.constant('c'); * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false - */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. + * _.functions(new Foo); + * // => ['a', 'b'] + */function functions(object){return object==null?[]:baseFunctions(object,keys(object));}/** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions * @example * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } * - * _.eq('a', Object('a')); - * // => false + * Foo.prototype.c = _.constant('c'); * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is greater than `other`. + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */function functionsIn(object){return object==null?[]:baseFunctions(object,keysIn(object));}/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. * @example * - * _.gt(3, 1); - * // => true + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * - * _.gt(3, 3); - * // => false + * _.get(object, 'a[0].b.c'); + * // => 3 * - * _.gt(1, 3); - * // => false - */ - var gt = createRelationalOperation(baseGt); - - /** - * Checks if `value` is greater than or equal to `other`. + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */function get(object,path,defaultValue){var result=object==null?undefined:baseGet(object,path);return result===undefined?defaultValue:result;}/** + * Checks if `path` is a direct property of `object`. * * @static + * @since 0.1.0 * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * - * _.gte(3, 1); + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); * // => true * - * _.gte(3, 3); + * _.has(object, 'a.b'); * // => true * - * _.gte(1, 3); + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); * // => false - */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); - - /** - * Checks if `value` is likely an `arguments` object. + */function has(object,path){return object!=null&&hasPath(object,path,baseHas);}/** + * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * - * _.isArguments(function() { return arguments; }()); + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); * // => true * - * _.isArguments([1, 2, 3]); + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * Checks if `value` is classified as an `Array` object. + */function hasIn(object,path){return object!=null&&hasPath(object,path,baseHasIn);}/** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. * @example * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false + * var object = { 'a': 1, 'b': 2, 'c': 1 }; * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is classified as an `ArrayBuffer` object. + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */var invert=createInverter(function(result,value,key){result[value]=key;},constant(identity));/** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. * @example * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true + * var object = { 'a': 1, 'b': 2, 'c': 1 }; * - * _.isArrayBuffer(new Array(2)); - * // => false - */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */var invertBy=createInverter(function(result,value,key){if(hasOwnProperty.call(result,value)){result[value].push(key);}else{result[value]=[key];}},getIteratee);/** + * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example * - * _.isArrayLike(document.body.children); - * // => true + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * - * _.isArrayLike('abc'); - * // => true + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */var invoke=baseRest(baseInvoke);/** + * Creates an array of the own enumerable property names of `object`. * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. * @example * - * _.isArrayLikeObject([1, 2, 3]); - * // => true + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.isArrayLikeObject(document.body.children); - * // => true + * Foo.prototype.c = 3; * - * _.isArrayLikeObject('abc'); - * // => false + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is classified as a boolean primitive or object. + * _.keys('hi'); + * // => ['0', '1'] + */function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object);}/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. * @example * - * _.isBoolean(false); - * // => true + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); - } - - /** - * Checks if `value` is a buffer. + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,true):baseKeysIn(object);}/** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues * @example * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Date` object. + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */function mapKeys(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value);});return result;}/** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys * @example * - * _.isDate(new Date); - * // => true + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; * - * _.isDate('Mon April 23 2012'); - * // => false - */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - - /** - * Checks if `value` is likely a DOM element. + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */function mapValues(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object));});return result;}/** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. * @example * - * _.isElement(document.body); - * // => true + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; * - * _.isElement(''); - * // => false - */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } - - /** - * Checks if `value` is an empty object, collection, map, or set. + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; * - * Objects are considered empty if they have no own enumerable string keyed - * properties. + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */var merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex);});/** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. * @example * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } * - * _.isEmpty([1, 2, 3]); - * // => false + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; * - * _.isEmpty({ 'a': 1 }); - * // => false - */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } - } - return true; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */var mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer);});/** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. + * **Note:** This method is considerably slower than `_.pick`. * * @static - * @memberOf _ * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. * @example * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true + * var object = { 'a': 1, 'b': '2', 'c': 3 }; * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */var omit=flatRest(function(object,paths){var result={};if(object==null){return result;}var isDeep=false;paths=arrayMap(paths,function(path){path=castPath(path,object);isDeep||(isDeep=path.length>1);return path;});copyObject(object,getAllKeysIn(object),result);if(isDeep){result=baseClone(result,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG,customOmitClone);}var length=paths.length;while(length--){baseUnset(result,paths[length]);}return result;});/** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. * @example * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } + * var object = { 'a': 1, 'b': '2', 'c': 3 }; * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)));}/** + * Creates an object composed of the picked `object` properties. * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example * - * _.isEqualWith(array, other, customizer); - * // => true - */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; - } - - /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */var pick=flatRest(function(object,paths){return object==null?{}:basePick(object,paths);});/** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. * @example * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false - */ - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); - } - - /** - * Checks if `value` is a finite primitive number. + * var object = { 'a': 1, 'b': '2', 'c': 3 }; * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */function pickBy(object,predicate){if(object==null){return{};}var props=arrayMap(getAllKeysIn(object),function(prop){return[prop];});predicate=getIteratee(predicate);return basePickBy(object,props,function(value,path){return predicate(value,path[0]);});}/** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. * * @static - * @memberOf _ * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. * @example * - * _.isFinite(3); - * // => true + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * - * _.isFinite(Number.MIN_VALUE); - * // => true + * _.result(object, 'a[0].b.c1'); + * // => 3 * - * _.isFinite(Infinity); - * // => false + * _.result(object, 'a[0].b.c2'); + * // => 4 * - * _.isFinite('3'); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); - } - - /** - * Checks if `value` is classified as a `Function` object. + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */function result(object,path,defaultValue){path=castPath(path,object);var index=-1,length=path.length;// Ensure the loop is entered when path is empty. +if(!length){length=1;object=undefined;}while(++index true + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is an integer. + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */function set(object,path,value){return object==null?object:baseSet(object,path,value);}/** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. * @example * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); - } - - /** - * Checks if `value` is a valid array-like length. + * var object = {}; * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */function setWith(object,path,value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseSet(object,path,value,customizer);}/** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. * @example * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.isLength(Infinity); - * // => false + * Foo.prototype.c = 3; * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */var toPairs=createToPairs(keys);/** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. * @example * - * _.isObject({}); - * // => true + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */var toPairsIn=createToPairs(keysIn);/** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example * - * _.isObject([1, 2, 3]); - * // => true + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] * - * _.isObject(_.noop); - * // => true + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */function transform(object,iteratee,accumulator){var isArr=isArray(object),isArrLike=isArr||isBuffer(object)||isTypedArray(object);iteratee=getIteratee(iteratee,4);if(accumulator==null){var Ctor=object&&object.constructor;if(isArrLike){accumulator=isArr?new Ctor():[];}else if(isObject(object)){accumulator=isFunction(Ctor)?baseCreate(getPrototype(object)):{};}else{accumulator={};}}(isArrLike?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object);});return accumulator;}/** + * Removes the property at `path` of `object`. * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". + * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * - * _.isObjectLike({}); + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); * // => true * - * _.isObjectLike([1, 2, 3]); + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); * // => true * - * _.isObjectLike(_.noop); - * // => false + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */function unset(object,path){return object==null?true:baseUnset(object,path);}/** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** - * Checks if `value` is classified as a `Map` object. + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. * @example * - * _.isMap(new Map); - * // => true + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * - * _.isMap(new WeakMap); - * // => false - */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - - /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */function update(object,path,updater){return object==null?object:baseUpdate(object,path,castFunction(updater));}/** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. * @example * - * var object = { 'a': 1, 'b': 2 }; + * var object = {}; * - * _.isMatch(object, { 'b': 2 }); - * // => true + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */function updateWith(object,path,updater,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseUpdate(object,path,castFunction(updater),customizer);}/** + * Creates an array of the own enumerable string keyed property values of `object`. * - * _.isMatch(object, { 'b': 1 }); - * // => false - */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } - - /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). + * **Note:** Non-object values are coerced to objects. * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. * @example * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); + * function Foo() { + * this.a = 1; + * this.b = 2; * } * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } + * Foo.prototype.c = 3; * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) * - * _.isMatchWith(object, source, customizer); - * // => true - */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); - } - - /** - * Checks if `value` is `NaN`. + * _.values('hi'); + * // => ['h', 'i'] + */function values(object){return object==null?[]:baseValues(object,keys(object));}/** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. + * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. * @example * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is a pristine native function. + * Foo.prototype.c = 3; * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */function valuesIn(object){return object==null?[]:baseValues(object,keysIn(object));}/*------------------------------------------------------------------------*//** + * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. * @example * - * _.isNative(Array.prototype.push); - * // => true + * _.clamp(-10, -5, 5); + * // => -5 * - * _.isNative(_); - * // => false - */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } - - /** - * Checks if `value` is `null`. + * _.clamp(10, -5, 5); + * // => 5 + */function clamp(number,lower,upper){if(upper===undefined){upper=lower;lower=undefined;}if(upper!==undefined){upper=toNumber(upper);upper=upper===upper?upper:0;}if(lower!==undefined){lower=toNumber(lower);lower=lower===lower?lower:0;}return baseClamp(toNumber(number),lower,upper);}/** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight * @example * - * _.isNull(null); + * _.inRange(3, 2, 4); * // => true * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is `null` or `undefined`. + * _.inRange(4, 8); + * // => true * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example + * _.inRange(4, 2); + * // => false * - * _.isNil(null); - * // => true + * _.inRange(2, 2); + * // => false * - * _.isNil(void 0); + * _.inRange(1.2, 2); * // => true * - * _.isNil(NaN); + * _.inRange(5.2, 4); * // => false - */ - function isNil(value) { - return value == null; - } - - /** - * Checks if `value` is classified as a `Number` primitive or object. * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. + * _.inRange(-3, -2, -6); + * // => true + */function inRange(number,start,end){start=toFinite(start);if(end===undefined){end=start;start=0;}else{end=toFinite(end);}number=toNumber(number);return baseInRange(number,start,end);}/** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. * @example * - * _.isNumber(3); - * // => true + * _.random(0, 5); + * // => an integer between 0 and 5 * - * _.isNumber(Number.MIN_VALUE); - * // => true + * _.random(5); + * // => also an integer between 0 and 5 * - * _.isNumber(Infinity); - * // => true + * _.random(5, true); + * // => a floating-point number between 0 and 5 * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */function random(lower,upper,floating){if(floating&&typeof floating!='boolean'&&isIterateeCall(lower,upper,floating)){upper=floating=undefined;}if(floating===undefined){if(typeof upper=='boolean'){floating=upper;upper=undefined;}else if(typeof lower=='boolean'){floating=lower;lower=undefined;}}if(lower===undefined&&upper===undefined){lower=0;upper=1;}else{lower=toFinite(lower);if(upper===undefined){upper=lower;lower=0;}else{upper=toFinite(upper);}}if(lower>upper){var temp=lower;lower=upper;upper=temp;}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat('1e-'+((rand+'').length-1))),upper);}return baseRandom(lower,upper);}/*------------------------------------------------------------------------*//** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. * @example * - * function Foo() { - * this.a = 1; - * } + * _.camelCase('Foo Bar'); + * // => 'fooBar' * - * _.isPlainObject(new Foo); - * // => false + * _.camelCase('--foo-bar--'); + * // => 'fooBar' * - * _.isPlainObject([1, 2, 3]); - * // => false + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return result+(index?capitalize(word):word);});/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * Checks if `value` is classified as a `RegExp` object. + * _.capitalize('FRED'); + * // => 'Fred' + */function capitalize(string){return upperFirst(toString(string).toLowerCase());}/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. * @example * - * _.isRegExp(/abc/); + * _.deburr('déjà vu'); + * // => 'deja vu' + */function deburr(string){string=toString(string);return string&&string.replace(reLatin,deburrLetter).replace(reComboMark,'');}/** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); * // => true * - * _.isRegExp('/abc/'); + * _.endsWith('abc', 'b'); * // => false - */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - - /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * _.endsWith('abc', 'b', 2); + * // => true + */function endsWith(string,target,position){string=toString(string);target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;position-=target.length;return position>=0&&string.slice(position,end)==target;}/** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. * @example * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */function escape(string){string=toString(string);return string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string;}/** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * - * _.isSafeInteger(Infinity); - * // => false + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example * - * _.isSafeInteger('3'); - * // => false - */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is classified as a `Set` object. + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */function escapeRegExp(string){string=toString(string);return string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,'\\$&'):string;}/** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. * @example * - * _.isSet(new Set); - * // => true + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' * - * _.isSet(new WeakSet); - * // => false - */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - - /** - * Checks if `value` is classified as a `String` primitive or object. + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */var kebabCase=createCompounder(function(result,word,index){return result+(index?'-':'')+word.toLowerCase();});/** + * Converts `string`, as space separated words, to lower case. * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. * @example * - * _.isString('abc'); - * // => true + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); - } - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */var lowerCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toLowerCase();});/** + * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. * @example * - * _.isSymbol(Symbol.iterator); - * // => true + * _.lowerFirst('Fred'); + * // => 'fred' * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** - * Checks if `value` is classified as a typed array. + * _.lowerFirst('FRED'); + * // => 'fRED' + */var lowerFirst=createCaseFirst('toLowerCase');/** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. * @example * - * _.isTypedArray(new Uint8Array); - * // => true + * _.pad('abc', 8); + * // => ' abc ' * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** - * Checks if `value` is `undefined`. + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */function pad(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length){return string;}var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars);}/** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. * @example * - * _.isUndefined(void 0); - * // => true + * _.padEnd('abc', 6); + * // => 'abc ' * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - /** - * Checks if `value` is classified as a `WeakMap` object. + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */function padEnd(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength true + * _.padStart('abc', 6); + * // => ' abc' * - * _.isWeakMap(new Map); - * // => false - */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } - - /** - * Checks if `value` is classified as a `WeakSet` object. + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */function padStart(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength true + * _.parseInt('08'); + * // => 8 * - * _.isWeakSet(new Set); - * // => false - */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - - /** - * Checks if `value` is less than `other`. + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */function parseInt(string,radix,guard){if(guard||radix==null){radix=0;}else if(radix){radix=+radix;}return nativeParseInt(toString(string).replace(reTrimStart,''),radix||0);}/** + * Repeats the given string `n` times. * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. * @example * - * _.lt(1, 3); - * // => true + * _.repeat('*', 3); + * // => '***' * - * _.lt(3, 3); - * // => false + * _.repeat('abc', 2); + * // => 'abcabc' * - * _.lt(3, 1); - * // => false - */ - var lt = createRelationalOperation(baseLt); - - /** - * Checks if `value` is less than or equal to `other`. + * _.repeat('abc', 0); + * // => '' + */function repeat(string,n,guard){if(guard?isIterateeCall(string,n,guard):n===undefined){n=1;}else{n=toInteger(n);}return baseRepeat(toString(string),n);}/** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. * @example * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false - */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); - - /** - * Converts `value` to an array. + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2]);}/** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. * @example * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] + * _.snakeCase('fooBar'); + * // => 'foo_bar' * - * _.toArray(1); - * // => [] + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */var snakeCase=createCompounder(function(result,word,index){return result+(index?'_':'')+word.toLowerCase();});/** + * Splits `string` by `separator`. * - * _.toArray(null); - * // => [] - */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); - } - - /** - * Converts `value` to a finite number. + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. * @example * - * _.toFinite(3.2); - * // => 3.2 + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */function split(string,separator,limit){if(limit&&typeof limit!='number'&&isIterateeCall(string,separator,limit)){separator=limit=undefined;}limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0;if(!limit){return[];}string=toString(string);if(string&&(typeof separator=='string'||separator!=null&&!isRegExp(separator))){separator=baseToString(separator);if(!separator&&hasUnicode(string)){return castSlice(stringToArray(string),0,limit);}}return string.split(separator,limit);}/** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' * - * _.toFinite('3.2'); - * // => 3.2 - */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; - } - - /** - * Converts `value` to an integer. + * _.startCase('fooBar'); + * // => 'Foo Bar' * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */var startCase=createCompounder(function(result,word,index){return result+(index?' ':'')+upperFirst(word);});/** + * Checks if `string` starts with the given target string. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. * @example * - * _.toInteger(3.2); - * // => 3 + * _.startsWith('abc', 'a'); + * // => true * - * _.toInteger(Number.MIN_VALUE); - * // => 0 + * _.startsWith('abc', 'b'); + * // => false * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 + * _.startsWith('abc', 'b', 1); + * // => true + */function startsWith(string,target,position){string=toString(string);position=position==null?0:baseClamp(toInteger(position),0,string.length);target=baseToString(target);return string.slice(position,position+target.length)==target;}/** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. * - * _.toInteger('3.2'); - * // => 3 - */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; - } - - /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. * @example * - * _.toLength(3.2); - * // => 3 + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' * - * _.toLength(Number.MIN_VALUE); - * // => 0 + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': '