From 89f5929abccc333c73a165c10c98ce7624965c4c Mon Sep 17 00:00:00 2001 From: Tom Jenkinson Date: Tue, 10 Aug 2021 15:39:25 +0100 Subject: [PATCH 1/6] do not discard prerelease string --- lib/versions.js | 27 ++++++++++++++++++++++----- test/versions.test.js | 16 +++++++++++----- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/lib/versions.js b/lib/versions.js index 157551fd5..553c0ed2f 100644 --- a/lib/versions.js +++ b/lib/versions.js @@ -5,9 +5,16 @@ const splitSemVer = (input, versionKey = 'version') => { return null } - const version = input.inc - ? semver.inc(input[versionKey], input.inc, true) - : semver.parse(input[versionKey]) + let version + if (input.inc) { + version = semver.inc(input[versionKey], input.inc, true) + } else { + const semverVersion = semver.parse(input[versionKey]) + if (!semverVersion) { + return null + } + version = semverVersion.version + } return { ...input, @@ -36,14 +43,24 @@ const getTemplatableVersion = (input) => { return templatableVersion } +const toSemver = (version) => { + const result = semver.parse(version) + if (result) { + return result + } + + // doesn't handle prerelease + return semver.coerce(version) +} + const coerceVersion = (input) => { if (!input) { return null } return typeof input === 'object' - ? semver.coerce(input.tag_name) || semver.coerce(input.name) - : semver.coerce(input) + ? toSemver(input.tag_name) || toSemver(input.name) + : toSemver(input) } module.exports.getVersionInfo = ( diff --git a/test/versions.test.js b/test/versions.test.js index c7a18b2af..0721468d2 100644 --- a/test/versions.test.js +++ b/test/versions.test.js @@ -36,14 +36,20 @@ describe('versions', () => { }) it('handles alpha/beta releases', () => { - const versionInfo = getVersionInfo({ - tag_name: 'v10.0.3-alpha', - name: 'Some release', - }) + const versionInfo = getVersionInfo( + { + tag_name: 'v10.0.3-alpha', + name: 'Some release', + }, + null, + 'v10.0.3-alpha' + ) expect(versionInfo.$NEXT_MAJOR_VERSION.version).toEqual('11.0.0') expect(versionInfo.$NEXT_MINOR_VERSION.version).toEqual('10.1.0') - expect(versionInfo.$NEXT_PATCH_VERSION.version).toEqual('10.0.4') + expect(versionInfo.$NEXT_PATCH_VERSION.version).toEqual('10.0.3') + expect(versionInfo.$INPUT_VERSION.version).toEqual('10.0.3-alpha') + expect(versionInfo.$RESOLVED_VERSION.version).toEqual('10.0.3-alpha') }) it('returns undefined if no version was found in tag or name', () => { From f899c403d3e21b058bcd0c9292032a941b4fea54 Mon Sep 17 00:00:00 2001 From: Tom Jenkinson Date: Tue, 10 Aug 2021 15:45:35 +0100 Subject: [PATCH 2/6] simplify splitSemVer --- lib/versions.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/versions.js b/lib/versions.js index 553c0ed2f..45f3c6605 100644 --- a/lib/versions.js +++ b/lib/versions.js @@ -9,11 +9,7 @@ const splitSemVer = (input, versionKey = 'version') => { if (input.inc) { version = semver.inc(input[versionKey], input.inc, true) } else { - const semverVersion = semver.parse(input[versionKey]) - if (!semverVersion) { - return null - } - version = semverVersion.version + version = input[versionKey].version } return { From 2a2cb8f094fb0d8af596bc143316e871e17beb54 Mon Sep 17 00:00:00 2001 From: Tom Jenkinson Date: Tue, 10 Aug 2021 17:13:46 +0100 Subject: [PATCH 3/6] add $COMPLETE version template variable --- README.md | 11 ++++++----- lib/versions.js | 1 + 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 58c0bb573..1b70e895b 100644 --- a/README.md +++ b/README.md @@ -160,11 +160,12 @@ You can use any of the following variables in your `template`, `name-template` a You can use any of the following variables in `version-template` to format the `$NEXT_{PATCH,MINOR,MAJOR}_VERSION` variables: -| Variable | Description | -| -------- | ------------------------- | -| `$PATCH` | The patch version number. | -| `$MINOR` | The minor version number. | -| `$MAJOR` | The major version number. | +| Variable | Description | +| ----------- | ------------------------------------------------------------ | +| `$PATCH` | The patch version number. | +| `$MINOR` | The minor version number. | +| `$MAJOR` | The major version number. | +| `$COMPLETE` | The complete version string (including any prerelease info). | ## Version Resolver diff --git a/lib/versions.js b/lib/versions.js index 45f3c6605..c21e50c4f 100644 --- a/lib/versions.js +++ b/lib/versions.js @@ -18,6 +18,7 @@ const splitSemVer = (input, versionKey = 'version') => { $MAJOR: semver.major(version), $MINOR: semver.minor(version), $PATCH: semver.patch(version), + $COMPLETE: version, } } From 749016be61c53ca04c280d84df3fcb11be1c177e Mon Sep 17 00:00:00 2001 From: Tom Jenkinson Date: Mon, 6 Sep 2021 18:38:39 +0100 Subject: [PATCH 4/6] use ternary Co-authored-by: Joseph Petersen --- lib/versions.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/versions.js b/lib/versions.js index 956822392..54dd7d038 100644 --- a/lib/versions.js +++ b/lib/versions.js @@ -5,12 +5,9 @@ const splitSemVer = (input, versionKey = 'version') => { return null } - let version - if (input.inc) { - version = semver.inc(input[versionKey], input.inc, true) - } else { - version = input[versionKey].version - } + const version = input.inc + ? semver.inc(input[versionKey], input.inc, true) + : input[versionKey].version return { ...input, From cd1744c29808cd40bcbca9fe08a3e000df2fddea Mon Sep 17 00:00:00 2001 From: Tom Jenkinson Date: Mon, 6 Sep 2021 18:41:34 +0100 Subject: [PATCH 5/6] update dist --- dist/index.js | 112225 +++++++++++++++++++++++------------------------ 1 file changed, 55730 insertions(+), 56495 deletions(-) diff --git a/dist/index.js b/dist/index.js index b748a8e34..3f35ffd02 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1319,7 +1319,7 @@ const splitSemVer = (input, versionKey = 'version') => { const version = input.inc ? semver.inc(input[versionKey], input.inc, true) - : semver.parse(input[versionKey]) + : input[versionKey].version return { ...input, @@ -1327,6 +1327,7 @@ const splitSemVer = (input, versionKey = 'version') => { $MAJOR: semver.major(version), $MINOR: semver.minor(version), $PATCH: semver.patch(version), + $COMPLETE: version, } } @@ -1393,14 +1394,24 @@ const getTemplatableVersion = (input) => { return templatableVersion } +const toSemver = (version) => { + const result = semver.parse(version) + if (result) { + return result + } + + // doesn't handle prerelease + return semver.coerce(version) +} + const coerceVersion = (input) => { if (!input) { return null } return typeof input === 'object' - ? semver.coerce(input.tag_name) || semver.coerce(input.name) - : semver.coerce(input) + ? toSemver(input.tag_name) || toSemver(input.name) + : toSemver(input) } module.exports.getVersionInfo = ( @@ -12952,7 +12963,7 @@ exports.Octokit = Octokit; Object.defineProperty(exports, "__esModule", ({ value: true })); -var isPlainObject = __nccwpck_require__(70558); +var isPlainObject = __nccwpck_require__(63287); var universalUserAgent = __nccwpck_require__(45030); function lowercaseKeys(object) { @@ -13340,52 +13351,6 @@ exports.endpoint = endpoint; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 70558: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; - - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; -} - -exports.isPlainObject = isPlainObject; - - /***/ }), /***/ 88467: @@ -15316,7 +15281,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var endpoint = __nccwpck_require__(59440); var universalUserAgent = __nccwpck_require__(45030); -var isPlainObject = __nccwpck_require__(49062); +var isPlainObject = __nccwpck_require__(63287); var nodeFetch = _interopDefault(__nccwpck_require__(80467)); var requestError = __nccwpck_require__(10537); @@ -15458,52 +15423,6 @@ exports.request = request; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 49062: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; - - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; -} - -exports.isPlainObject = isPlainObject; - - /***/ }), /***/ 18513: @@ -26668,7 +26587,7 @@ exports.browserPerformanceTimeOrigin = (function () { */ var Negotiator = __nccwpck_require__(95385) -var mime = __nccwpck_require__(66918) +var mime = __nccwpck_require__(43583) /** * Module exports. @@ -26893,220 +26812,6 @@ function validMime (type) { } -/***/ }), - -/***/ 2122: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -/** - * Module exports. - */ - -module.exports = __nccwpck_require__(12016) - - -/***/ }), - -/***/ 66918: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var db = __nccwpck_require__(2122) -var extname = __nccwpck_require__(85622).extname - -/** - * Module variables. - * @private - */ - -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i - -/** - * Module exports. - * @public - */ - -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) - -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) - -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] - - if (mime && mime.charset) { - return mime.charset - } - - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } - - return false -} - -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ - -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } - - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str - - if (!mime) { - return false - } - - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } - - return mime -} - -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] - - if (!exts || !exts.length) { - return false - } - - return exts[0] -} - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ - -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } - - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - - if (!extension) { - return false - } - - return exports.types[extension] || false -} - -/** - * Populate the extensions and types maps. - * @private - */ - -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] - - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions - - if (!exts || !exts.length) { - return - } - - // mime -> extensions - extensions[type] = exts - - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] - - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) - - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } - - // set the extension -> mime - types[extension] = type - } - }) -} - - /***/ }), /***/ 49690: @@ -38262,4964 +37967,5677 @@ module['exports'] = colors; /***/ }), -/***/ 89296: -/***/ (function(module) { - -/* global define */ -(function (root, factory) { - /* istanbul ignore next */ - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (true) { - module.exports = factory(); - } else {} -}(this, function () { +/***/ 85443: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; +var util = __nccwpck_require__(31669); +var Stream = __nccwpck_require__(92413).Stream; +var DelayedStream = __nccwpck_require__(18611); - function indexOrEnd(str, q) { - return str.indexOf(q) === -1 ? str.length : str.indexOf(q); - } +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; - function split(v) { - var c = v.replace(/^v/, '').replace(/\+.*$/, ''); - var patchIndex = indexOrEnd(c, '-'); - var arr = c.substring(0, patchIndex).split('.'); - arr.push(c.substring(patchIndex + 1)); - return arr; - } + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); - function tryParse(v) { - return isNaN(Number(v)) ? v : Number(v); - } +CombinedStream.create = function(options) { + var combinedStream = new this(); - function validate(version) { - if (typeof version !== 'string') { - throw new TypeError('Invalid argument expected string'); - } - if (!semver.test(version)) { - throw new Error('Invalid argument not valid semver (\''+version+'\' received)'); - } + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; } - function compareVersions(v1, v2) { - [v1, v2].forEach(validate); + return combinedStream; +}; - var s1 = split(v1); - var s2 = split(v2); +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; - for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { - var n1 = parseInt(s1[i] || 0, 10); - var n2 = parseInt(s2[i] || 0, 10); +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); - if (n1 > n2) return 1; - if (n2 > n1) return -1; + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; } - var sp1 = s1[s1.length - 1]; - var sp2 = s2[s2.length - 1]; - - if (sp1 && sp2) { - var p1 = sp1.split('.').map(tryParse); - var p2 = sp2.split('.').map(tryParse); - - for (i = 0; i < Math.max(p1.length, p2.length); i++) { - if (p1[i] === undefined || typeof p2[i] === 'string' && typeof p1[i] === 'number') return -1; - if (p2[i] === undefined || typeof p1[i] === 'string' && typeof p2[i] === 'number') return 1; + this._handleErrors(stream); - if (p1[i] > p2[i]) return 1; - if (p2[i] > p1[i]) return -1; - } - } else if (sp1 || sp2) { - return sp1 ? -1 : 1; + if (this.pauseStreams) { + stream.pause(); } + } - return 0; - }; - - var allowedOperators = [ - '>', - '>=', - '=', - '<', - '<=' - ]; + this._streams.push(stream); + return this; +}; - var operatorResMap = { - '>': [1], - '>=': [0, 1], - '=': [0], - '<=': [-1, 0], - '<': [-1] - }; +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; - function validateOperator(op) { - if (typeof op !== 'string') { - throw new TypeError('Invalid operator type, expected string but got ' + typeof op); - } - if (allowedOperators.indexOf(op) === -1) { - throw new TypeError('Invalid operator, expected one of ' + allowedOperators.join('|')); - } - } +CombinedStream.prototype._getNext = function() { + this._currentStream = null; - compareVersions.validate = function(version) { - return typeof version === 'string' && semver.test(version); + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call } - compareVersions.compare = function (v1, v2, operator) { - // Validate operator - validateOperator(operator); - - // since result of compareVersions can only be -1 or 0 or 1 - // a simple map can be used to replace switch - var res = compareVersions(v1, v2); - return operatorResMap[operator].indexOf(res) > -1; + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; } +}; - return compareVersions; -})); - - -/***/ }), - -/***/ 53921: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); + if (typeof stream == 'undefined') { + this.end(); + return; + } -/** - * Module exports. - * @public - */ + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } -module.exports = contentDisposition -module.exports.parse = parse + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } -/** - * Module dependencies. - * @private - */ + this._pipeNext(stream); + }.bind(this)); +}; -var basename = __nccwpck_require__(85622).basename -var Buffer = __nccwpck_require__(21867).Buffer +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private - */ + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + var value = stream; + this.write(value); + this._getNext(); +}; -/** - * RegExp to match percent encoding escape. - * @private - */ +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; -/** - * RegExp to match non-latin1 characters. - * @private - */ +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - * @private - */ +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; -var QUOTE_REGEXP = /([\\"])/g +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; -/** - * RegExp for various RFC 2616 grammar - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = - * @private - */ +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } -/** - * RegExp for various RFC 5987 grammar - * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - * @private - */ + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; -/** - * RegExp for various RFC 6266 grammar - * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = - * @private - */ + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + self.dataSize += stream.dataSize; + }); -/** - * Create an attachment Content-Disposition header. - * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public - */ + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; -function contentDisposition (filename, options) { - var opts = options || {} +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; - // get type - var type = opts.type || 'attachment' - // get parameters - var params = createparams(filename, opts.fallback) +/***/ }), - // format into string - return format(new ContentDisposition(type, params)) -} +/***/ 61904: +/***/ ((module, exports, __nccwpck_require__) => { /** - * Create parameters object from filename and fallback. - * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private + * Module dependencies. */ -function createparams (filename, fallback) { - if (filename === undefined) { - return - } - - var params = {} - - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } +const EventEmitter = __nccwpck_require__(28614).EventEmitter; +const spawn = __nccwpck_require__(63129).spawn; +const path = __nccwpck_require__(85622); +const fs = __nccwpck_require__(35747); - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } +// @ts-check - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } +class Option { + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} description + * @api public + */ - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') + constructor(flags, description) { + this.flags = flags; + this.required = flags.includes('<'); // A value must be supplied when the option is specified. + this.optional = flags.includes('['); // A value is optional when the option is specified. + // variadic test ignores et al which might be used to describe custom splitting of single argument + this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + const optionFlags = _parseOptionFlags(flags); + this.short = optionFlags.shortFlag; + this.long = optionFlags.longFlag; + this.negate = false; + if (this.long) { + this.negate = this.long.startsWith('--no-'); + } + this.description = description || ''; + this.defaultValue = undefined; } - // restrict to file base name - var name = basename(filename) + /** + * Return option name. + * + * @return {string} + * @api private + */ - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) + name() { + if (this.long) { + return this.long.replace(/^--/, ''); + } + return this.short.replace(/^-/, ''); + }; - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + /** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {string} + * @api private + */ - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } + attributeName() { + return camelcase(this.name().replace(/^no-/, '')); + }; - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name - } + /** + * Check if `arg` matches the short or long flag. + * + * @param {string} arg + * @return {boolean} + * @api private + */ - return params + is(arg) { + return this.short === arg || this.long === arg; + }; } /** - * Format object to Content-Disposition header. - * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @private + * CommanderError class + * @class */ - -function format (obj) { - var parameters = obj.parameters - var type = obj.type - - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') +class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {number} exitCode suggested exit code which could be used with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @constructor + */ + constructor(exitCode, code, message) { + super(message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + this.nestedError = undefined; } +} - // start with normalized type - var string = String(type).toLowerCase() +class Command extends EventEmitter { + /** + * Initialize a new `Command`. + * + * @param {string} [name] + * @api public + */ - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + constructor(name) { + super(); + this.commands = []; + this.options = []; + this.parent = null; + this._allowUnknownOption = false; + this._args = []; + this.rawArgs = null; + this._scriptPath = null; + this._name = name || ''; + this._optionValues = {}; + this._storeOptionsAsProperties = true; // backwards compatible by default + this._storeOptionsAsPropertiesCalled = false; + this._passCommandToAction = true; // backwards compatible by default + this._actionResults = []; + this._actionHandler = null; + this._executableHandler = false; + this._executableFile = null; // custom name for executable + this._defaultCommandName = null; + this._exitCallback = null; + this._aliases = []; + this._combineFlagAndOptionalValue = true; - for (var i = 0; i < params.length; i++) { - param = params[i] + this._hidden = false; + this._hasHelpOption = true; + this._helpFlags = '-h, --help'; + this._helpDescription = 'display help for command'; + this._helpShortFlag = '-h'; + this._helpLongFlag = '--help'; + this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false + this._helpCommandName = 'help'; + this._helpCommandnameAndArgs = 'help [command]'; + this._helpCommandDescription = 'display help for command'; + } - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) + /** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * Examples: + * + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or `this` for executable command + * @api public + */ - string += '; ' + param + '=' + val + command(nameAndArgs, actionOptsOrExecDesc, execOpts) { + let desc = actionOptsOrExecDesc; + let opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; } - } - - return string -} + opts = opts || {}; + const args = nameAndArgs.split(/ +/); + const cmd = this.createCommand(args.shift()); -/** - * Decode a RFC 6987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ + if (desc) { + cmd.description(desc); + cmd._executableHandler = true; + } + if (opts.isDefault) this._defaultCommandName = cmd._name; -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) + cmd._hidden = !!(opts.noHelp || opts.hidden); + cmd._hasHelpOption = this._hasHelpOption; + cmd._helpFlags = this._helpFlags; + cmd._helpDescription = this._helpDescription; + cmd._helpShortFlag = this._helpShortFlag; + cmd._helpLongFlag = this._helpLongFlag; + cmd._helpCommandName = this._helpCommandName; + cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs; + cmd._helpCommandDescription = this._helpCommandDescription; + cmd._exitCallback = this._exitCallback; + cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; + cmd._passCommandToAction = this._passCommandToAction; + cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue; - if (!match) { - throw new TypeError('invalid extended field value') - } + cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor + this.commands.push(cmd); + cmd._parseExpectedArgs(args); + cmd.parent = this; - var charset = match[1].toLowerCase() - var encoded = match[2] - var value + if (desc) return this; + return cmd; + }; - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + /** + * Factory routine to create a new unattached command. + * + * See .command() for creating an attached subcommand, which uses this routine to + * create the command. You can override createCommand to customise subcommands. + * + * @param {string} [name] + * @return {Command} new command + * @api public + */ - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = Buffer.from(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') - } + createCommand(name) { + return new Command(name); + }; - return value -} + /** + * Add a prepared subcommand. + * + * See .command() for creating an attached subcommand which inherits settings from its parent. + * + * @param {Command} cmd - new subcommand + * @param {Object} [opts] - configuration options + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @private - */ + addCommand(cmd, opts) { + if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') -} + // To keep things simple, block automatic name generation for deeply nested executables. + // Fail fast and detect when adding rather than later when parsing. + function checkExplicitNames(commandArray) { + commandArray.forEach((cmd) => { + if (cmd._executableHandler && !cmd._executableFile) { + throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`); + } + checkExplicitNames(cmd.commands); + }); + } + checkExplicitNames(cmd.commands); -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @public - */ + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') - } + this.commands.push(cmd); + cmd.parent = this; + return this; + }; - var match = DISPOSITION_TYPE_REGEXP.exec(string) + /** + * Define argument syntax for the command. + * + * @api public + */ - if (!match) { - throw new TypeError('invalid type format') - } + arguments(desc) { + return this._parseExpectedArgs(desc.split(/ +/)); + }; - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() + /** + * Override default decision whether to add implicit help command. + * + * addHelpCommand() // force on + * addHelpCommand(false); // force off + * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details + * + * @return {Command} `this` command for chaining + * @api public + */ - var key - var names = [] - var params = {} - var value + addHelpCommand(enableOrNameAndArgs, description) { + if (enableOrNameAndArgs === false) { + this._hasImplicitHelpCommand = false; + } else { + this._hasImplicitHelpCommand = true; + if (typeof enableOrNameAndArgs === 'string') { + this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; + this._helpCommandnameAndArgs = enableOrNameAndArgs; + } + this._helpCommandDescription = description || this._helpCommandDescription; + } + return this; + }; - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index + /** + * @return {boolean} + * @api private + */ - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') + _lazyHasImplicitHelpCommand() { + if (this._hasImplicitHelpCommand === undefined) { + this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); } + return this._hasImplicitHelpCommand; + }; - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} `this` command for chaining + * @api private + */ - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') - } + _parseExpectedArgs(args) { + if (!args.length) return; + args.forEach((arg) => { + const argDetails = { + required: false, + name: '', + variadic: false + }; - names.push(key) + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + this._args.push(argDetails); + } + }); + this._args.forEach((arg, i) => { + if (arg.variadic && i < this._args.length - 1) { + throw new Error(`only the last argument can be variadic '${arg.name}'`); + } + }); + return this; + }; - // overwrite existing value - params[key] = value - continue - } + /** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} `this` command for chaining + * @api public + */ - if (typeof params[key] === 'string') { - continue + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = (err) => { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; } + return this; + }; - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') + /** + * Call process.exit, and _exitCallback if defined. + * + * @param {number} exitCode exit code for using with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @return never + * @api private + */ + + _exit(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. } + process.exit(exitCode); + }; - params[key] = value - } + /** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} `this` command for chaining + * @api public + */ - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } + action(fn) { + const listener = (args) => { + // The .action callback takes an extra parameter which is the command or options. + const expectedArgsCount = this._args.length; + const actionArgs = args.slice(0, expectedArgsCount); + if (this._passCommandToAction) { + actionArgs[expectedArgsCount] = this; + } else { + actionArgs[expectedArgsCount] = this.opts(); + } + // Add the extra arguments so available too. + if (args.length > expectedArgsCount) { + actionArgs.push(args.slice(expectedArgsCount)); + } - return new ContentDisposition(type, params) -} + const actionResult = fn.apply(this, actionArgs); + // Remember result in case it is async. Assume parseAsync getting called on root. + let rootCommand = this; + while (rootCommand.parent) { + rootCommand = rootCommand.parent; + } + rootCommand._actionResults.push(actionResult); + }; + this._actionHandler = listener; + return this; + }; -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @private - */ + /** + * Internal routine to check whether there is a clash storing option value with a Command property. + * + * @param {Option} option + * @api private + */ -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} + _checkForOptionNameClash(option) { + if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) { + // Storing options safely, or user has been explicit and up to them. + return; + } + // User may override help, and hard to tell if worth warning. + if (option.name() === 'help') { + return; + } -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ + const commandProperty = this._getOptionValue(option.attributeName()); + if (commandProperty === undefined) { + // no clash + return; + } -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() -} + let foundClash = true; + if (option.negate) { + // It is ok if define foo before --no-foo. + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + foundClash = !this._findOption(positiveLongFlag); + } else if (option.long) { + const negativeLongFlag = option.long.replace(/^--/, '--no-'); + foundClash = !this._findOption(negativeLongFlag); + } -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ + if (foundClash) { + throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command +- call storeOptionsAsProperties(false) to store option values safely, +- or call storeOptionsAsProperties(true) to suppress this check, +- or change option name -function qstring (val) { - var str = String(val) +Read more on https://git.io/JJc0W`); + } + }; - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + /** + * Internal implementation shared by .option() and .requiredOption() + * + * @param {Object} config + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api private + */ -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @private - */ + _optionEx(config, flags, description, fn, defaultValue) { + const option = new Option(flags, description); + const oname = option.name(); + const name = option.attributeName(); + option.mandatory = !!config.mandatory; -function ustring (val) { - var str = String(val) + this._checkForOptionNameClash(option); - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. + // No longer documented in README, but still present for backwards compatibility. + const regex = fn; + fn = (val, def) => { + const m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } - return 'UTF-8\'\'' + encoded -} + // preassign default value for --no-*, [optional], , or plain flag if boolean value + if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { + // when --no-foo we make sure default is true, unless a --foo option is already defined + if (option.negate) { + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true; + } + // preassign only if we have a default + if (defaultValue !== undefined) { + this._setOptionValue(name, defaultValue); + option.defaultValue = defaultValue; + } + } -/** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor - */ + // register the option + this.options.push(option); -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters -} + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, (val) => { + const oldValue = this._getOptionValue(name); + // custom processing + if (val !== null && fn) { + val = fn(val, oldValue === undefined ? defaultValue : oldValue); + } else if (val !== null && option.variadic) { + if (oldValue === defaultValue || !Array.isArray(oldValue)) { + val = [val]; + } else { + val = oldValue.concat(val); + } + } -/***/ }), + // unassigned or boolean value + if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') { + // if no value, negate false, and we have a default, then use it! + if (val == null) { + this._setOptionValue(name, option.negate + ? false + : defaultValue || true); + } else { + this._setOptionValue(name, val); + } + } else if (val !== null) { + // reassign + this._setOptionValue(name, option.negate ? false : val); + } + }); -/***/ 99915: -/***/ ((__unused_webpack_module, exports) => { + return this; + }; -"use strict"; -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ + option(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); + }; + /** + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ -/** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + requiredOption(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); + }; -/** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + /** + * Alter parsing of short flags with optional values. + * + * Examples: + * + * // for `.option('-f,--flag [value]'): + * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour + * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` + * + * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag. + * @api public + */ + combineFlagAndOptionalValue(arg) { + this._combineFlagAndOptionalValue = (arg === undefined) || arg; + return this; + }; -/** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g + /** + * Allow unknown options on the command line. + * + * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ + allowUnknownOption(arg) { + this._allowUnknownOption = (arg === undefined) || arg; + return this; + }; -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Module exports. - * @public - */ + storeOptionsAsProperties(value) { + this._storeOptionsAsPropertiesCalled = true; + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + throw new Error('call .storeOptionsAsProperties() before adding options'); + } + return this; + }; -exports.format = format -exports.parse = parse + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public - */ + passCommandToAction(value) { + this._passCommandToAction = (value === undefined) || value; + return this; + }; -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } + /** + * Store option value + * + * @param {string} key + * @param {Object} value + * @api private + */ - var parameters = obj.parameters - var type = obj.type + _setOptionValue(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } + }; - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') - } + /** + * Retrieve option value + * + * @param {string} key + * @return {Object} value + * @api private + */ - var string = type + _getOptionValue(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; + }; - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parse(process.argv); + * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] - optional, defaults to process.argv + * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron + * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' + * @return {Command} `this` command for chaining + * @api public + */ - for (var i = 0; i < params.length; i++) { - param = params[i] + parse(argv, parseOptions) { + if (argv !== undefined && !Array.isArray(argv)) { + throw new Error('first parameter to parse must be array or undefined'); + } + parseOptions = parseOptions || {}; - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') + // Default to using process.argv + if (argv === undefined) { + argv = process.argv; + // @ts-ignore + if (process.versions && process.versions.electron) { + parseOptions.from = 'electron'; } - - string += '; ' + param + '=' + qstring(parameters[param]) } - } - - return string -} - -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } - - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string + this.rawArgs = argv.slice(); - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } + // make it a little easier for callers by supporting various argv conventions + let userArgs; + switch (parseOptions.from) { + case undefined: + case 'node': + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + break; + case 'electron': + // @ts-ignore + if (process.defaultApp) { + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + } else { + userArgs = argv.slice(1); + } + break; + case 'user': + userArgs = argv.slice(0); + break; + default: + throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); + } + if (!this._scriptPath && process.mainModule) { + this._scriptPath = process.mainModule.filename; + } - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() + // Guess name, used in usage in help. + this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') - } + // Let's go! + this._parseCommand([], userArgs); - var obj = new ContentType(type.toLowerCase()) + return this; + }; - // parse parameters - if (index !== -1) { - var key - var match - var value + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parseAsync(process.argv); + * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] + * @param {Object} [parseOptions] + * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' + * @return {Promise} + * @api public + */ - PARAM_REGEXP.lastIndex = index + parseAsync(argv, parseOptions) { + this.parse(argv, parseOptions); + return Promise.all(this._actionResults).then(() => this); + }; - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } + /** + * Execute a sub-command executable. + * + * @api private + */ - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + _executeSubCommand(subcommand, args) { + args = args.slice(); + let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. + const sourceExt = ['.js', '.ts', '.tsx', '.mjs']; - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } + // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. + this._checkForMissingMandatoryOptions(); - obj.parameters[key] = value + // Want the entry script as the reference for command name and directory for searching for other files. + let scriptPath = this._scriptPath; + // Fallback in case not set, due to how Command created or called. + if (!scriptPath && process.mainModule) { + scriptPath = process.mainModule.filename; } - if (index !== header.length) { - throw new TypeError('invalid parameter format') + let baseDir; + try { + const resolvedLink = fs.realpathSync(scriptPath); + baseDir = path.dirname(resolvedLink); + } catch (e) { + baseDir = '.'; // dummy, probably not going to find executable! } - } - return obj -} + // name of the subcommand, like `pm-install` + let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; + if (subcommand._executableFile) { + bin = subcommand._executableFile; + } -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - -function getcontenttype (obj) { - var header + const localBin = path.join(baseDir, bin); + if (fs.existsSync(localBin)) { + // prefer local `./` to bin in the $PATH + bin = localBin; + } else { + // Look for source files. + sourceExt.forEach((ext) => { + if (fs.existsSync(`${localBin}${ext}`)) { + bin = `${localBin}${ext}`; + } + }); + } + launchWithNode = sourceExt.includes(path.extname(bin)); - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] - } + let proc; + if (process.platform !== 'win32') { + if (launchWithNode) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') - } + proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = spawn(bin, args, { stdio: 'inherit' }); + } + } else { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } - return header -} + const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach((signal) => { + // @ts-ignore + process.on(signal, () => { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @private - */ + // By default terminate process when spawned process terminates. + // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on('close', process.exit.bind(process)); + } else { + proc.on('close', () => { + exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); + }); + } + proc.on('error', (err) => { + // @ts-ignore + if (err.code === 'ENOENT') { + const executableMissing = `'${bin}' does not exist + - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead + - if the default executable name is not suitable, use the executableFile option to supply a custom name`; + throw new Error(executableMissing); + // @ts-ignore + } else if (err.code === 'EACCES') { + throw new Error(`'${bin}' not executable`); + } + if (!exitCallback) { + process.exit(1); + } else { + const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); + wrappedError.nestedError = err; + exitCallback(wrappedError); + } + }); -function qstring (val) { - var str = String(val) + // Store the reference to the child process + this.runningCommand = proc; + }; - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } + /** + * @api private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this._helpAndError(); - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') - } + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); + } else { + subCommand._parseCommand(operands, unknown); + } + }; - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + /** + * Process arguments in context of this command. + * + * @api private + */ -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type -} + _parseCommand(operands, unknown) { + const parsed = this.parseOptions(unknown); + operands = operands.concat(parsed.operands); + unknown = parsed.unknown; + this.args = operands.concat(unknown); + if (operands && this._findCommand(operands[0])) { + this._dispatchSubcommand(operands[0], operands.slice(1), unknown); + } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) { + if (operands.length === 1) { + this.help(); + } else { + this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); + } + } else if (this._defaultCommandName) { + outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command + this._dispatchSubcommand(this._defaultCommandName, operands, unknown); + } else { + if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { + // probably missing subcommand and no handler, user needs help + this._helpAndError(); + } -/***/ }), + outputHelpIfRequested(this, parsed.unknown); + this._checkForMissingMandatoryOptions(); + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); + } -/***/ 61579: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (this._actionHandler) { + const args = this.args.slice(); + this._args.forEach((arg, i) => { + if (arg.required && args[i] == null) { + this.missingArgument(arg.name); + } else if (arg.variadic) { + args[i] = args.splice(i); + } + }); -/** - * Module dependencies. - */ + this._actionHandler(args); + this.emit('command:' + this.name(), operands, unknown); + } else if (operands.length) { + if (this._findCommand('*')) { + this._dispatchSubcommand('*', operands, unknown); + } else if (this.listenerCount('command:*')) { + this.emit('command:*', operands, unknown); + } else if (this.commands.length) { + this.unknownCommand(); + } + } else if (this.commands.length) { + // This command has subcommands and nothing hooked up at this level, so display help. + this._helpAndError(); + } else { + // fall through for caller to handle after calling .parse() + } + } + }; -var crypto = __nccwpck_require__(76417); + /** + * Find matching command. + * + * @api private + */ + _findCommand(name) { + if (!name) return undefined; + return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); + }; -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @api private + */ -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; + _findOption(arg) { + return this.options.find(option => option.is(arg)); + }; -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ + /** + * Display an error message if a mandatory option does not have a value. + * Lazy calling after checking for help flags from leaf subcommand. + * + * @api private + */ -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf('.')) - , mac = exports.sign(str, secret); - - return sha1(mac) == sha1(val) ? str : false; -}; + _checkForMissingMandatoryOptions() { + // Walk up hierarchy so can call in subcommand after checking for displaying help. + for (let cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { + cmd.missingMandatoryOptionValue(anOption); + } + }); + } + }; -/** - * Private - */ + /** + * Parse options from `argv` removing known options, + * and return argv split into operands and unknown arguments. + * + * Examples: + * + * argv => operands, unknown + * --known kkk op => [op], [] + * op --known kkk => [op], [] + * sub --unknown uuu op => [sub], [--unknown uuu op] + * sub -- --unknown uuu op => [sub --unknown uuu op], [] + * + * @param {String[]} argv + * @return {{operands: String[], unknown: String[]}} + * @api public + */ -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} + parseOptions(argv) { + const operands = []; // operands, not options or values + const unknown = []; // first unknown option and remaining unknown args + let dest = operands; + const args = argv.slice(); + function maybeOption(arg) { + return arg.length > 1 && arg[0] === '-'; + } -/***/ }), + // parse options + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); -/***/ 93658: -/***/ ((__unused_webpack_module, exports) => { + // literal + if (arg === '--') { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; + if (maybeOption(arg)) { + const option = this._findOption(arg); + // recognised option, call listener to assign value with possible custom processing + if (option) { + if (option.required) { + const value = args.shift(); + if (value === undefined) this.optionMissingArgument(option); + this.emit(`option:${option.name()}`, value); + } else if (option.optional) { + let value = null; + // historical behaviour is optional value is following arg unless an option + if (args.length > 0 && !maybeOption(args[0])) { + value = args.shift(); + } + this.emit(`option:${option.name()}`, value); + } else { // boolean flag + this.emit(`option:${option.name()}`); + } + activeVariadicOption = option.variadic ? option : null; + continue; + } + } + // Look for combo options following single dash, eat first one if known. + if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + const option = this._findOption(`-${arg[1]}`); + if (option) { + if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { + // option with value following in same argument + this.emit(`option:${option.name()}`, arg.slice(2)); + } else { + // boolean option, emit and put back remainder of arg for further processing + this.emit(`option:${option.name()}`); + args.unshift(`-${arg.slice(2)}`); + } + continue; + } + } -/** - * Module exports. - * @public - */ + // Look for known long flag with value, like --foo=bar + if (/^--[^=]+=/.test(arg)) { + const index = arg.indexOf('='); + const option = this._findOption(arg.slice(0, index)); + if (option && (option.required || option.optional)) { + this.emit(`option:${option.name()}`, arg.slice(index + 1)); + continue; + } + } -exports.parse = parse; -exports.serialize = serialize; + // looks like an option but unknown, unknowns from here + if (arg.length > 1 && arg[0] === '-') { + dest = unknown; + } -/** - * Module variables. - * @private - */ + // add arg + dest.push(arg); + } -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; + return { operands, unknown }; + }; -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ + /** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ + opts() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + const result = {}; + const len = this.options.length; -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + for (let i = 0; i < len; i++) { + const key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; + } -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ + return this._optionValues; + }; -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } + /** + * Argument `name` is missing. + * + * @param {string} name + * @api private + */ - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); + }; - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); + /** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {string} [flag] + * @api private + */ - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; + optionMissingArgument(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; + } else { + message = `error: option '${option.flags}' argument missing`; } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); + }; - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); - - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); - } - } + missingMandatoryOptionValue(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); + }; - return obj; -} + /** + * Unknown option `flag`. + * + * @param {string} flag + * @api private + */ -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ + unknownOption(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); + }; -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; + /** + * Unknown command. + * + * @api private + */ - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } + unknownCommand() { + const partCommands = [this.name()]; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + partCommands.unshift(parentCmd.name()); + } + const fullCommand = partCommands.join(' '); + const message = `error: unknown command '${this.args[0]}'.` + + (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : ''); + console.error(message); + this._exit(1, 'commander.unknownCommand', message); + }; - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {string} str + * @param {string} [flags] + * @param {string} [description] + * @return {this | string} `this` command for chaining, or version string if no arguments + * @api public + */ - var value = enc(val); + version(str, flags, description) { + if (str === undefined) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + const versionOption = new Option(flags, description); + this._versionOptionName = versionOption.attributeName(); + this.options.push(versionOption); + this.on('option:' + versionOption.name(), () => { + process.stdout.write(str + '\n'); + this._exit(0, 'commander.version', str); + }); + return this; + }; - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } + /** + * Set the description to `str`. + * + * @param {string} str + * @param {Object} [argsDescription] + * @return {string|Command} + * @api public + */ - var str = name + '=' + value; + description(str, argsDescription) { + if (str === undefined && argsDescription === undefined) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; + }; - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; - if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); - str += '; Max-Age=' + Math.floor(maxAge); - } + /** + * Set an alias for the command. + * + * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. + * + * @param {string} [alias] + * @return {string|Command} + * @api public + */ - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); + alias(alias) { + if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility + + let command = this; + if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { + // assume adding alias for last added executable subcommand, rather than this + command = this.commands[this.commands.length - 1]; } - str += '; Domain=' + opt.domain; - } + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } + command._aliases.push(alias); + return this; + }; - str += '; Path=' + opt.path; - } + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {string[]|Command} + * @api public + */ - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); + aliases(aliases) { + // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). + if (aliases === undefined) return this._aliases; + + aliases.forEach((alias) => this.alias(alias)); + return this; + }; + + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ + + usage(str) { + if (str === undefined) { + if (this._usage) return this._usage; + + const args = this._args.map((arg) => { + return humanReadableArgName(arg); + }); + return [].concat( + (this.options.length || this._hasHelpOption ? '[options]' : []), + (this.commands.length ? '[command]' : []), + (this._args.length ? args : []) + ).join(' '); } - str += '; Expires=' + opt.expires.toUTCString(); - } + this._usage = str; + return this; + }; - if (opt.httpOnly) { - str += '; HttpOnly'; - } + /** + * Get or set the name of the command + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ - if (opt.secure) { - str += '; Secure'; - } + name(str) { + if (str === undefined) return this._name; + this._name = str; + return this; + }; - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; + /** + * Return prepared commands. + * + * @return {Array} + * @api private + */ - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); + prepareCommands() { + const commandDetails = this.commands.filter((cmd) => { + return !cmd._hidden; + }).map((cmd) => { + const args = cmd._args.map((arg) => { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); + + if (this._lazyHasImplicitHelpCommand()) { + commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); } - } + return commandDetails; + }; - return str; -} + /** + * Return the largest command length. + * + * @return {number} + * @api private + */ -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ + largestCommandLength() { + const commands = this.prepareCommands(); + return commands.reduce((max, command) => { + return Math.max(max, command[0].length); + }, 0); + }; -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} + /** + * Return the largest option length. + * + * @return {number} + * @api private + */ + largestOptionLength() { + const options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); -/***/ }), + return options.reduce((max, option) => { + return Math.max(max, option.flags.length); + }, 0); + }; -/***/ 65507: -/***/ ((__unused_webpack_module, exports) => { + /** + * Return the largest arg length. + * + * @return {number} + * @api private + */ -/* jshint node: true */ -(function () { - "use strict"; + largestArgLength() { + return this._args.reduce((max, arg) => { + return Math.max(max, arg.name.length); + }, 0); + }; - function CookieAccessInfo(domain, path, secure, script) { - if (this instanceof CookieAccessInfo) { - this.domain = domain || undefined; - this.path = path || "/"; - this.secure = !!secure; - this.script = !!script; - return this; - } - return new CookieAccessInfo(domain, path, secure, script); + /** + * Return the pad width. + * + * @return {number} + * @api private + */ + + padWidth() { + let width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } } - CookieAccessInfo.All = Object.freeze(Object.create(null)); - exports.CookieAccessInfo = CookieAccessInfo; - function Cookie(cookiestr, request_domain, request_path) { - if (cookiestr instanceof Cookie) { - return cookiestr; - } - if (this instanceof Cookie) { - this.name = null; - this.value = null; - this.expiration_date = Infinity; - this.path = String(request_path || "/"); - this.explicit_path = false; - this.domain = request_domain || null; - this.explicit_domain = false; - this.secure = false; //how to define default? - this.noscript = false; //httponly - if (cookiestr) { - this.parse(cookiestr, request_domain, request_path); - } - return this; - } - return new Cookie(cookiestr, request_domain, request_path); + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } } - exports.Cookie = Cookie; - Cookie.prototype.toString = function toString() { - var str = [this.name + "=" + this.value]; - if (this.expiration_date !== Infinity) { - str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); - } - if (this.domain) { - str.push("domain=" + this.domain); - } - if (this.path) { - str.push("path=" + this.path); - } - if (this.secure) { - str.push("secure"); - } - if (this.noscript) { - str.push("httponly"); - } - return str.join("; "); - }; + return width; + }; - Cookie.prototype.toValueString = function toValueString() { - return this.name + "=" + this.value; - }; + /** + * Return help for options. + * + * @return {string} + * @api private + */ - var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; - Cookie.prototype.parse = function parse(str, request_domain, request_path) { - if (this instanceof Cookie) { - var parts = str.split(";").filter(function (value) { - return !!value; - }); - var i; + optionHelp() { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; + function padOptionDetails(flags, description) { + return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2); + }; - var pair = parts[0].match(/([^=]+)=([\s\S]*)/); - if (!pair) { - console.warn("Invalid cookie header encountered. Header: '"+str+"'"); - return; - } + // Explicit options (including version) + const help = this.options.map((option) => { + const fullDesc = option.description + + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + return padOptionDetails(option.flags, fullDesc); + }); - var key = pair[1]; - var value = pair[2]; - if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) { - console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'"); - return; - } + // Implicit help + const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag); + const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag); + if (showShortHelpFlag || showLongHelpFlag) { + let helpFlags = this._helpFlags; + if (!showShortHelpFlag) { + helpFlags = this._helpLongFlag; + } else if (!showLongHelpFlag) { + helpFlags = this._helpShortFlag; + } + help.push(padOptionDetails(helpFlags, this._helpDescription)); + } - this.name = key; - this.value = value; + return help.join('\n'); + }; - for (i = 1; i < parts.length; i += 1) { - pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); - key = pair[1].trim().toLowerCase(); - value = pair[2]; - switch (key) { - case "httponly": - this.noscript = true; - break; - case "expires": - this.expiration_date = value ? - Number(Date.parse(value)) : - Infinity; - break; - case "path": - this.path = value ? - value.trim() : - ""; - this.explicit_path = true; - break; - case "domain": - this.domain = value ? - value.trim() : - ""; - this.explicit_domain = !!this.domain; - break; - case "secure": - this.secure = true; - break; - } - } + /** + * Return command help documentation. + * + * @return {string} + * @api private + */ - if (!this.explicit_path) { - this.path = request_path || "/"; - } - if (!this.explicit_domain) { - this.domain = request_domain; - } + commandHelp() { + if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; - return this; - } - return new Cookie().parse(str, request_domain, request_path); - }; + const commands = this.prepareCommands(); + const width = this.padWidth(); - Cookie.prototype.matches = function matches(access_info) { - if (access_info === CookieAccessInfo.All) { - return true; - } - if (this.noscript && access_info.script || - this.secure && !access_info.secure || - !this.collidesWith(access_info)) { - return false; - } - return true; - }; + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; - Cookie.prototype.collidesWith = function collidesWith(access_info) { - if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { - return false; - } - if (this.path && access_info.path.indexOf(this.path) !== 0) { - return false; - } - if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { - return false; - } - var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); - var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); - if (cookie_domain === access_domain) { - return true; - } - if (cookie_domain) { - if (!this.explicit_domain) { - return false; // we already checked if the domains were exactly the same - } - var wildcard = access_domain.indexOf(cookie_domain); - if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { - return false; - } - return true; - } - return true; - }; + return [ + 'Commands:', + commands.map((cmd) => { + const desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); + }; - function CookieJar() { - var cookies, cookies_list, collidable_cookie; - if (this instanceof CookieJar) { - cookies = Object.create(null); //name: [Cookie] + /** + * Return program help documentation. + * + * @return {string} + * @api public + */ - this.setCookie = function setCookie(cookie, request_domain, request_path) { - var remove, i; - cookie = new Cookie(cookie, request_domain, request_path); - //Delete the cookie if the set is past the current time - remove = cookie.expiration_date <= Date.now(); - if (cookies[cookie.name] !== undefined) { - cookies_list = cookies[cookie.name]; - for (i = 0; i < cookies_list.length; i += 1) { - collidable_cookie = cookies_list[i]; - if (collidable_cookie.collidesWith(cookie)) { - if (remove) { - cookies_list.splice(i, 1); - if (cookies_list.length === 0) { - delete cookies[cookie.name]; - } - return false; - } - cookies_list[i] = cookie; - return cookie; - } - } - if (remove) { - return false; - } - cookies_list.push(cookie); - return cookie; - } - if (remove) { - return false; - } - cookies[cookie.name] = [cookie]; - return cookies[cookie.name]; - }; - //returns a cookie - this.getCookie = function getCookie(cookie_name, access_info) { - var cookie, i; - cookies_list = cookies[cookie_name]; - if (!cookies_list) { - return; - } - for (i = 0; i < cookies_list.length; i += 1) { - cookie = cookies_list[i]; - if (cookie.expiration_date <= Date.now()) { - if (cookies_list.length === 0) { - delete cookies[cookie.name]; - } - continue; - } - - if (cookie.matches(access_info)) { - return cookie; - } - } - }; - //returns a list of cookies - this.getCookies = function getCookies(access_info) { - var matches = [], cookie_name, cookie; - for (cookie_name in cookies) { - cookie = this.getCookie(cookie_name, access_info); - if (cookie) { - matches.push(cookie); - } - } - matches.toString = function toString() { - return matches.join(":"); - }; - matches.toValueString = function toValueString() { - return matches.map(function (c) { - return c.toValueString(); - }).join(';'); - }; - return matches; - }; - - return this; - } - return new CookieJar(); - } - exports.CookieJar = CookieJar; + helpInformation() { + let desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; - //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. - CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { - cookies = Array.isArray(cookies) ? - cookies : - cookies.split(cookie_str_splitter); - var successful = [], - i, - cookie; - cookies = cookies.map(function(item){ - return new Cookie(item, request_domain, request_path); + const argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 5; + desc.push('Arguments:'); + this._args.forEach((arg) => { + desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4)); }); - for (i = 0; i < cookies.length; i += 1) { - cookie = cookies[i]; - if (this.setCookie(cookie, request_domain, request_path)) { - successful.push(cookie); - } - } - return successful; - }; -}()); + desc.push(''); + } + } + let cmdName = this._name; + if (this._aliases[0]) { + cmdName = cmdName + '|' + this._aliases[0]; + } + let parentCmdNames = ''; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; + } + const usage = [ + 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), + '' + ]; -/***/ }), + let cmds = []; + const commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; -/***/ 51512: -/***/ (function(module) { + let options = []; + if (this._hasHelpOption || this.options.length > 0) { + options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + } -/* - * Date Format 1.2.3 - * (c) 2007-2009 Steven Levithan - * MIT license - * - * Includes enhancements by Scott Trenda - * and Kris Kowal - * - * Accepts a date, a mask, or a date and a mask. - * Returns a formatted version of the given date. - * The date defaults to the current date/time. - * The mask defaults to dateFormat.masks.default. - */ + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); + }; -(function(global) { - 'use strict'; + /** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public + */ - var dateFormat = (function() { - var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|"[^"]*"|'[^']*'/g; - var timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g; - var timezoneClip = /[^-+\dA-Z]/g; - - // Regexes and supporting functions are cached through closure - return function (date, mask, utc, gmt) { - - // You can't provide utc if you skip other args (use the 'UTC:' mask prefix) - if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) { - mask = date; - date = undefined; - } - - date = date || new Date; - - if(!(date instanceof Date)) { - date = new Date(date); - } - - if (isNaN(date)) { - throw TypeError('Invalid date'); - } - - mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']); - - // Allow setting the utc/gmt argument via the mask - var maskSlice = mask.slice(0, 4); - if (maskSlice === 'UTC:' || maskSlice === 'GMT:') { - mask = mask.slice(4); - utc = true; - if (maskSlice === 'GMT:') { - gmt = true; - } - } - - var _ = utc ? 'getUTC' : 'get'; - var d = date[_ + 'Date'](); - var D = date[_ + 'Day'](); - var m = date[_ + 'Month'](); - var y = date[_ + 'FullYear'](); - var H = date[_ + 'Hours'](); - var M = date[_ + 'Minutes'](); - var s = date[_ + 'Seconds'](); - var L = date[_ + 'Milliseconds'](); - var o = utc ? 0 : date.getTimezoneOffset(); - var W = getWeek(date); - var N = getDayOfWeek(date); - var flags = { - d: d, - dd: pad(d), - ddd: dateFormat.i18n.dayNames[D], - dddd: dateFormat.i18n.dayNames[D + 7], - m: m + 1, - mm: pad(m + 1), - mmm: dateFormat.i18n.monthNames[m], - mmmm: dateFormat.i18n.monthNames[m + 12], - yy: String(y).slice(2), - yyyy: y, - h: H % 12 || 12, - hh: pad(H % 12 || 12), - H: H, - HH: pad(H), - M: M, - MM: pad(M), - s: s, - ss: pad(s), - l: pad(L, 3), - L: pad(Math.round(L / 10)), - t: H < 12 ? dateFormat.i18n.timeNames[0] : dateFormat.i18n.timeNames[1], - tt: H < 12 ? dateFormat.i18n.timeNames[2] : dateFormat.i18n.timeNames[3], - T: H < 12 ? dateFormat.i18n.timeNames[4] : dateFormat.i18n.timeNames[5], - TT: H < 12 ? dateFormat.i18n.timeNames[6] : dateFormat.i18n.timeNames[7], - Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''), - o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), - S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10], - W: W, - N: N - }; - - return mask.replace(token, function (match) { - if (match in flags) { - return flags[match]; - } - return match.slice(1, match.length - 1); - }); + outputHelp(cb) { + if (!cb) { + cb = (passthru) => { + return passthru; }; - })(); - - dateFormat.masks = { - 'default': 'ddd mmm dd yyyy HH:MM:ss', - 'shortDate': 'm/d/yy', - 'mediumDate': 'mmm d, yyyy', - 'longDate': 'mmmm d, yyyy', - 'fullDate': 'dddd, mmmm d, yyyy', - 'shortTime': 'h:MM TT', - 'mediumTime': 'h:MM:ss TT', - 'longTime': 'h:MM:ss TT Z', - 'isoDate': 'yyyy-mm-dd', - 'isoTime': 'HH:MM:ss', - 'isoDateTime': 'yyyy-mm-dd\'T\'HH:MM:sso', - 'isoUtcDateTime': 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\'', - 'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z' + } + const cbOutput = cb(this.helpInformation()); + if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { + throw new Error('outputHelp callback must return a string or a Buffer'); + } + process.stdout.write(cbOutput); + this.emit(this._helpLongFlag); }; - // Internationalization strings - dateFormat.i18n = { - dayNames: [ - 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', - 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' - ], - monthNames: [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', - 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' - ], - timeNames: [ - 'a', 'p', 'am', 'pm', 'A', 'P', 'AM', 'PM' - ] - }; + /** + * You can pass in flags and a description to override the help + * flags and help description for your command. Pass in false to + * disable the built-in help option. + * + * @param {string | boolean} [flags] + * @param {string} [description] + * @return {Command} `this` command for chaining + * @api public + */ -function pad(val, len) { - val = String(val); - len = len || 2; - while (val.length < len) { - val = '0' + val; - } - return val; -} + helpOption(flags, description) { + if (typeof flags === 'boolean') { + this._hasHelpOption = flags; + return this; + } + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; -/** - * Get the ISO 8601 week number - * Based on comments from - * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html - * - * @param {Object} `date` - * @return {Number} - */ -function getWeek(date) { - // Remove time components of date - var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate()); + const helpFlags = _parseOptionFlags(this._helpFlags); + this._helpShortFlag = helpFlags.shortFlag; + this._helpLongFlag = helpFlags.longFlag; - // Change date to Thursday same week - targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); + return this; + }; - // Take January 4th as it is always in week 1 (see ISO 8601) - var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); + /** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ - // Change date to Thursday same week - firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); + help(cb) { + this.outputHelp(cb); + // exitCode: preserving original behaviour which was calling process.exit() + // message: do not have all displayed text available so only passing placeholder. + this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); + }; - // Check if daylight-saving-time-switch occurred and correct for it - var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); - targetThursday.setHours(targetThursday.getHours() - ds); + /** + * Output help information and exit. Display for error situations. + * + * @api private + */ - // Number of weeks between target Thursday and first Thursday - var weekDiff = (targetThursday - firstThursday) / (86400000*7); - return 1 + Math.floor(weekDiff); -} + _helpAndError() { + this.outputHelp(); + // message: do not have all displayed text available so only passing placeholder. + this._exit(1, 'commander.help', '(outputHelp)'); + }; +}; /** - * Get ISO-8601 numeric representation of the day of the week - * 1 (for Monday) through 7 (for Sunday) - * - * @param {Object} `date` - * @return {Number} + * Expose the root command. */ -function getDayOfWeek(date) { - var dow = date.getDay(); - if(dow === 0) { - dow = 7; - } - return dow; -} + +exports = module.exports = new Command(); +exports.program = exports; // More explicit access to global command. /** - * kind-of shortcut - * @param {*} val - * @return {String} + * Expose classes */ -function kindOf(val) { - if (val === null) { - return 'null'; - } - - if (val === undefined) { - return 'undefined'; - } - - if (typeof val !== 'object') { - return typeof val; - } - - if (Array.isArray(val)) { - return 'array'; - } - - return {}.toString.call(val) - .slice(8, -1).toLowerCase(); -}; - - - - if (typeof define === 'function' && define.amd) { - define(function () { - return dateFormat; - }); - } else if (true) { - module.exports = dateFormat; - } else {} -})(this); - -/***/ }), - -/***/ 84697: -/***/ ((module) => { +exports.Command = Command; +exports.Option = Option; +exports.CommanderError = CommanderError; /** - * Helpers. + * Camel-case the given `flag` + * + * @param {string} flag + * @return {string} + * @api private */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; +function camelcase(flag) { + return flag.split('-').reduce((str, word) => { + return str + word[0].toUpperCase() + word.slice(1); + }); +} /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] + * Pad `str` to `width`. * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * @param {string} str + * @param {number} width + * @return {string} + * @api private */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +function pad(str, width) { + const len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} /** - * Parse the given `str` and return milliseconds. + * Wraps the given string with line breaks at the specified width while breaking + * words and indenting every but the first line on the left. * - * @param {String} str - * @return {Number} + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} * @api private */ +function wrap(str, width, indent) { + const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); + const lines = str.match(regex) || []; + return lines.map((line, i) => { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); + } + return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); + }).join('\n'); +} -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } +/** + * Optionally wrap the given str to a max width of width characters per line + * while indenting with indent spaces. Do not wrap if insufficient width or + * string is manually formatted. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} + * @api private + */ +function optionalWrap(str, width, indent) { + // Detect manually wrapped and indented strings by searching for line breaks + // followed by multiple spaces/tabs. + if (str.match(/[\n]\s+/)) return str; + // Do not wrap to narrow columns (or can end up with a word per line). + const minWidth = 40; + if (width < minWidth) return str; + + return wrap(str, width, indent); } /** - * Short format for `ms`. + * Output help information if help flags specified * - * @param {Number} ms - * @return {String} + * @param {Command} cmd - command to output help for + * @param {Array} args - array of options to search for help flags * @api private */ -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; +function outputHelpIfRequested(cmd, args) { + const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); + if (helpOption) { + cmd.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); } - return ms + 'ms'; } /** - * Long format for `ms`. + * Takes an argument and returns its human readable equivalent for help usage. * - * @param {Number} ms - * @return {String} + * @param {Object} arg + * @return {string} * @api private */ -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); +function humanReadableArgName(arg) { + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} + +/** + * Parse the short and long flag out of something like '-m,--mixed ' + * + * @api private + */ + +function _parseOptionFlags(flags) { + let shortFlag; + let longFlag; + // Use original very loose parsing to maintain backwards compatibility for now, + // which allowed for example unintended `-sw, --short-word` [sic]. + const flagParts = flags.split(/[ |,]+/); + if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); + longFlag = flagParts.shift(); + // Add support for lone short flag without significantly changing parsing! + if (!shortFlag && /^-[^-]$/.test(longFlag)) { + shortFlag = longFlag; + longFlag = undefined; } - return ms + ' ms'; + return { shortFlag, longFlag }; } /** - * Pluralization helper. + * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * + * @param {string[]} args - array of arguments from node.execArgv + * @returns {string[]} + * @api private */ -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +function incrementNodeInspectorPort(args) { + // Testing for these options: + // --inspect[=[host:]port] + // --inspect-brk[=[host:]port] + // --inspect-port=[host:]port + return args.map((arg) => { + if (!arg.startsWith('--inspect')) { + return arg; + } + let debugOption; + let debugHost = '127.0.0.1'; + let debugPort = '9229'; + let match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; + } + + if (debugOption && debugPort !== '0') { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + return arg; + }); } /***/ }), -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 89296: +/***/ (function(module) { -/* eslint-env browser */ +/* global define */ +(function (root, factory) { + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (true) { + module.exports = factory(); + } else {} +}(this, function () { -/** - * This is the web browser implementation of `debug()`. + var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; + + function indexOrEnd(str, q) { + return str.indexOf(q) === -1 ? str.length : str.indexOf(q); + } + + function split(v) { + var c = v.replace(/^v/, '').replace(/\+.*$/, ''); + var patchIndex = indexOrEnd(c, '-'); + var arr = c.substring(0, patchIndex).split('.'); + arr.push(c.substring(patchIndex + 1)); + return arr; + } + + function tryParse(v) { + return isNaN(Number(v)) ? v : Number(v); + } + + function validate(version) { + if (typeof version !== 'string') { + throw new TypeError('Invalid argument expected string'); + } + if (!semver.test(version)) { + throw new Error('Invalid argument not valid semver (\''+version+'\' received)'); + } + } + + function compareVersions(v1, v2) { + [v1, v2].forEach(validate); + + var s1 = split(v1); + var s2 = split(v2); + + for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { + var n1 = parseInt(s1[i] || 0, 10); + var n2 = parseInt(s2[i] || 0, 10); + + if (n1 > n2) return 1; + if (n2 > n1) return -1; + } + + var sp1 = s1[s1.length - 1]; + var sp2 = s2[s2.length - 1]; + + if (sp1 && sp2) { + var p1 = sp1.split('.').map(tryParse); + var p2 = sp2.split('.').map(tryParse); + + for (i = 0; i < Math.max(p1.length, p2.length); i++) { + if (p1[i] === undefined || typeof p2[i] === 'string' && typeof p1[i] === 'number') return -1; + if (p2[i] === undefined || typeof p1[i] === 'string' && typeof p2[i] === 'number') return 1; + + if (p1[i] > p2[i]) return 1; + if (p2[i] > p1[i]) return -1; + } + } else if (sp1 || sp2) { + return sp1 ? -1 : 1; + } + + return 0; + }; + + var allowedOperators = [ + '>', + '>=', + '=', + '<', + '<=' + ]; + + var operatorResMap = { + '>': [1], + '>=': [0, 1], + '=': [0], + '<=': [-1, 0], + '<': [-1] + }; + + function validateOperator(op) { + if (typeof op !== 'string') { + throw new TypeError('Invalid operator type, expected string but got ' + typeof op); + } + if (allowedOperators.indexOf(op) === -1) { + throw new TypeError('Invalid operator, expected one of ' + allowedOperators.join('|')); + } + } + + compareVersions.validate = function(version) { + return typeof version === 'string' && semver.test(version); + } + + compareVersions.compare = function (v1, v2, operator) { + // Validate operator + validateOperator(operator); + + // since result of compareVersions can only be -1 or 0 or 1 + // a simple map can be used to replace switch + var res = compareVersions(v1, v2); + return operatorResMap[operator].indexOf(res) > -1; + } + + return compareVersions; +})); + + +/***/ }), + +/***/ 53921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed */ -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); /** - * Colors. + * Module exports. + * @public */ -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; +module.exports = contentDisposition +module.exports.parse = parse /** - * 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 + * Module dependencies. + * @private */ -// eslint-disable-next-line complexity -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' || window.process.__nwjs)) { - return true; - } +var basename = __nccwpck_require__(85622).basename +var Buffer = __nccwpck_require__(21867).Buffer - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ - // 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+)/)); -} +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex /** - * Colorize log arguments if enabled. - * - * @api public + * RegExp to match percent encoding escape. + * @private */ -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g - if (!this.useColors) { - return; - } +/** + * RegExp to match non-latin1 characters. + * @private + */ - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g - // 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 - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ - args.splice(lastC, 0, c); -} +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private */ -exports.log = console.debug || console.log || (() => {}); + +var QUOTE_REGEXP = /([\\"])/g /** - * Save `namespaces`. + * RegExp for various RFC 2616 grammar * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ /** - * Load `namespaces`. + * RegExp for various RFC 5987 grammar * - * @return {String} returns the previously persisted debug modes - * @api private + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // 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 r; -} +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * RegExp for various RFC 6266 grammar * - * @return {LocalStorage} - * @api private + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private */ -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public */ -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - +function contentDisposition (filename, options) { + var opts = options || {} -/***/ }), + // get type + var type = opts.type || 'attachment' -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // get parameters + var params = createparams(filename, opts.fallback) + // format into string + return format(new ContentDisposition(type, params)) +} /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private */ -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(84697); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +function createparams (filename, fallback) { + if (filename === undefined) { + return + } - /** - * The currently active debug mode names, and names to skip. - */ + var params = {} - createDebug.names = []; - createDebug.skips = []; + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } - /** - * 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". - */ - createDebug.formatters = {}; + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + // restrict to file base name + var name = basename(filename) - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - const self = debug; + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } - args[0] = createDebug.coerce(args[0]); + return params +} - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); +function format (obj) { + var parameters = obj.parameters + var type = obj.type - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + // start with normalized type + var string = String(type).toLowerCase() - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + for (var i = 0; i < params.length; i++) { + param = params[i] - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, - set: v => { - enableOverride = v; - } - }); + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + string += '; ' + param + '=' + val + } + } - return debug; - } + return string +} - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) - createDebug.names = []; - createDebug.skips = []; + if (!match) { + throw new TypeError('invalid extended field value') + } - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + var charset = match[1].toLowerCase() + var encoded = match[2] + var value - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) - namespaces = split[i].replace(/\*/g, '.*?'); + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + return value +} - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} - let i; - let len; +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + var match = DISPOSITION_TYPE_REGEXP.exec(string) - return false; - } + if (!match) { + throw new TypeError('invalid type format') + } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + var key + var names = [] + var params = {} + var value - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index - createDebug.enable(createDebug.load()); + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } - return createDebug; -} + index += match[0].length + key = match[1].toLowerCase() + value = match[2] -module.exports = setup; + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + names.push(key) -/***/ }), + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // overwrite existing value + params[key] = value + continue + } -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ + if (typeof params[key] === 'string') { + continue + } -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); -} + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + params[key] = value + } -/***/ }), + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { + return new ContentDisposition(type, params) +} /** - * Module dependencies. + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private */ -const tty = __nccwpck_require__(33867); -const util = __nccwpck_require__(31669); +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} /** - * This is the Node.js implementation of `debug()`. + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private */ -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} /** - * Colors. + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private */ -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(59318); +function qstring (val) { + var str = String(val) - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' } /** - * Build up the default `inspectOpts` object from the environment variables. + * Encode a Unicode string for HTTP (RFC 5987). * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param {string} val + * @return {string} + * @private */ -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); +function ustring (val) { + var str = String(val) -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); + return 'UTF-8\'\'' + encoded } /** - * Adds ANSI color escape codes if enabled. + * Class for parsed Content-Disposition header for v8 optimization * - * @api public + * @public + * @param {string} type + * @param {object} parameters + * @constructor */ -function formatArgs(args) { - const {namespace: name, useColors} = this; +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} +/***/ }), -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} +/***/ 99915: +/***/ ((__unused_webpack_module, exports) => { -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. +"use strict"; +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed */ -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} + /** - * Save `namespaces`. + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 * - * @param {String} namespaces - * @api private + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** - * Load `namespaces`. + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 * - * @return {String} returns the previously persisted debug modes - * @api private + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g -function load() { - return process.env.DEBUG; -} +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g /** - * Init logic for `debug` instances. + * RegExp to match type in RFC 7231 sec 3.1.1.1 * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * media-type = type "/" subtype + * type = token + * subtype = token */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** - * Map %o to `util.inspect()`, all on a single line. + * Module exports. + * @public */ -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; +exports.format = format +exports.parse = parse /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public */ -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } -/***/ }), + var parameters = obj.parameters + var type = obj.type -/***/ 56323: -/***/ ((module) => { + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } -"use strict"; + var string = type + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; + for (var i = 0; i < params.length; i++) { + param = params[i] -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); + string += '; ' + param + '=' + qstring(parameters[param]) + } + } - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) + return string } -// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 -var canUseSymbol = typeof Symbol === 'function' && Symbol.for; -var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value -} + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return target.propertyIsEnumerable(symbol) - }) - : [] -} + var obj = new ContentType(type.toLowerCase()) -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) -} + // parse parameters + if (index !== -1) { + var key + var match + var value -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } -} + PARAM_REGEXP.lastIndex = index -// Protects from prototype poisoning and unexpected merging up the prototype chain. -function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. -} + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } -function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } + index += match[0].length + key = match[1].toLowerCase() + value = match[2] - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination -} + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } -function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; + obj.parameters[key] = value + } - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } + return obj } -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) -}; +function getcontenttype (obj) { + var header -var deepmerge_1 = deepmerge; + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } -module.exports = deepmerge_1; + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + return header +} -/***/ }), +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ -/***/ 18611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function qstring (val) { + var str = String(val) -var Stream = __nccwpck_require__(92413).Stream; -var util = __nccwpck_require__(31669); + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' } -util.inherits(DelayedStream, Stream); -DelayedStream.create = function(source, options) { - var delayedStream = new this(); +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } - delayedStream.source = source; +/***/ }), - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; +/***/ 61579: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } +/** + * Module dependencies. + */ - return delayedStream; -}; +var crypto = __nccwpck_require__(76417); -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); }; -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ - this.source.resume(); +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; }; -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; +/** + * Private + */ -DelayedStream.prototype.release = function() { - this._released = true; +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; +/***/ }), -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } +/***/ 65507: +/***/ ((__unused_webpack_module, exports) => { - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } +/* jshint node: true */ +(function () { + "use strict"; - this._bufferedEvents.push(args); -}; + function CookieAccessInfo(domain, path, secure, script) { + if (this instanceof CookieAccessInfo) { + this.domain = domain || undefined; + this.path = path || "/"; + this.secure = !!secure; + this.script = !!script; + return this; + } + return new CookieAccessInfo(domain, path, secure, script); + } + CookieAccessInfo.All = Object.freeze(Object.create(null)); + exports.CookieAccessInfo = CookieAccessInfo; -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } + function Cookie(cookiestr, request_domain, request_path) { + if (cookiestr instanceof Cookie) { + return cookiestr; + } + if (this instanceof Cookie) { + this.name = null; + this.value = null; + this.expiration_date = Infinity; + this.path = String(request_path || "/"); + this.explicit_path = false; + this.domain = request_domain || null; + this.explicit_domain = false; + this.secure = false; //how to define default? + this.noscript = false; //httponly + if (cookiestr) { + this.parse(cookiestr, request_domain, request_path); + } + return this; + } + return new Cookie(cookiestr, request_domain, request_path); + } + exports.Cookie = Cookie; - if (this.dataSize <= this.maxDataSize) { - return; - } + Cookie.prototype.toString = function toString() { + var str = [this.name + "=" + this.value]; + if (this.expiration_date !== Infinity) { + str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); + } + if (this.domain) { + str.push("domain=" + this.domain); + } + if (this.path) { + str.push("path=" + this.path); + } + if (this.secure) { + str.push("secure"); + } + if (this.noscript) { + str.push("httponly"); + } + return str.join("; "); + }; - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + Cookie.prototype.toValueString = function toValueString() { + return this.name + "=" + this.value; + }; + var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; + Cookie.prototype.parse = function parse(str, request_domain, request_path) { + if (this instanceof Cookie) { + var parts = str.split(";").filter(function (value) { + return !!value; + }); + var i; -/***/ }), + var pair = parts[0].match(/([^=]+)=([\s\S]*)/); + if (!pair) { + console.warn("Invalid cookie header encountered. Header: '"+str+"'"); + return; + } -/***/ 42342: -/***/ ((module) => { + var key = pair[1]; + var value = pair[2]; + if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) { + console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'"); + return; + } -"use strict"; + this.name = key; + this.value = value; + for (i = 1; i < parts.length; i += 1) { + pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); + key = pair[1].trim().toLowerCase(); + value = pair[2]; + switch (key) { + case "httponly": + this.noscript = true; + break; + case "expires": + this.expiration_date = value ? + Number(Date.parse(value)) : + Infinity; + break; + case "path": + this.path = value ? + value.trim() : + ""; + this.explicit_path = true; + break; + case "domain": + this.domain = value ? + value.trim() : + ""; + this.explicit_domain = !!this.domain; + break; + case "secure": + this.secure = true; + break; + } + } -/** - * Custom implementation of a double ended queue. - */ -function Denque(array) { - this._head = 0; - this._tail = 0; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); - } -} + if (!this.explicit_path) { + this.path = request_path || "/"; + } + if (!this.explicit_domain) { + this.domain = request_domain; + } -/** - * ------------- - * PUBLIC API - * ------------- - */ + return this; + } + return new Cookie().parse(str, request_domain, request_path); + }; -/** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} - */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; + Cookie.prototype.matches = function matches(access_info) { + if (access_info === CookieAccessInfo.All) { + return true; + } + if (this.noscript && access_info.script || + this.secure && !access_info.secure || + !this.collidesWith(access_info)) { + return false; + } + return true; + }; -/** - * Alias for peakAt() - * @param i - * @returns {*} - */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; + Cookie.prototype.collidesWith = function collidesWith(access_info) { + if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { + return false; + } + if (this.path && access_info.path.indexOf(this.path) !== 0) { + return false; + } + if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { + return false; + } + var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); + var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); + if (cookie_domain === access_domain) { + return true; + } + if (cookie_domain) { + if (!this.explicit_domain) { + return false; // we already checked if the domains were exactly the same + } + var wildcard = access_domain.indexOf(cookie_domain); + if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { + return false; + } + return true; + } + return true; + }; -/** - * Returns the first item in the list without removing it. - * @returns {*} - */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; + function CookieJar() { + var cookies, cookies_list, collidable_cookie; + if (this instanceof CookieJar) { + cookies = Object.create(null); //name: [Cookie] -/** - * Alias for peek() - * @returns {*} - */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; + this.setCookie = function setCookie(cookie, request_domain, request_path) { + var remove, i; + cookie = new Cookie(cookie, request_domain, request_path); + //Delete the cookie if the set is past the current time + remove = cookie.expiration_date <= Date.now(); + if (cookies[cookie.name] !== undefined) { + cookies_list = cookies[cookie.name]; + for (i = 0; i < cookies_list.length; i += 1) { + collidable_cookie = cookies_list[i]; + if (collidable_cookie.collidesWith(cookie)) { + if (remove) { + cookies_list.splice(i, 1); + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + return false; + } + cookies_list[i] = cookie; + return cookie; + } + } + if (remove) { + return false; + } + cookies_list.push(cookie); + return cookie; + } + if (remove) { + return false; + } + cookies[cookie.name] = [cookie]; + return cookies[cookie.name]; + }; + //returns a cookie + this.getCookie = function getCookie(cookie_name, access_info) { + var cookie, i; + cookies_list = cookies[cookie_name]; + if (!cookies_list) { + return; + } + for (i = 0; i < cookies_list.length; i += 1) { + cookie = cookies_list[i]; + if (cookie.expiration_date <= Date.now()) { + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + continue; + } -/** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) - */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; + if (cookie.matches(access_info)) { + return cookie; + } + } + }; + //returns a list of cookies + this.getCookies = function getCookies(access_info) { + var matches = [], cookie_name, cookie; + for (cookie_name in cookies) { + cookie = this.getCookie(cookie_name, access_info); + if (cookie) { + matches.push(cookie); + } + } + matches.toString = function toString() { + return matches.join(":"); + }; + matches.toValueString = function toValueString() { + return matches.map(function (c) { + return c.toValueString(); + }).join(';'); + }; + return matches; + }; -/** - * Returns the current length of the queue - * @return {Number} - */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); - } -}); + return this; + } + return new CookieJar(); + } + exports.CookieJar = CookieJar; -/** - * Return the number of items on the list, or 0 if empty. - * @returns {number} - */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. + CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { + cookies = Array.isArray(cookies) ? + cookies : + cookies.split(cookie_str_splitter); + var successful = [], + i, + cookie; + cookies = cookies.map(function(item){ + return new Cookie(item, request_domain, request_path); + }); + for (i = 0; i < cookies.length; i += 1) { + cookie = cookies[i]; + if (this.setCookie(cookie, request_domain, request_path)) { + successful.push(cookie); + } + } + return successful; + }; +}()); -/** - * Add an item at the beginning of the list. - * @param item - */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; -/** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; +/***/ }), -/** - * Add an item to the bottom of the list. - * @param item +/***/ 51512: +/***/ (function(module) { + +/* + * Date Format 1.2.3 + * (c) 2007-2009 Steven Levithan + * MIT license + * + * Includes enhancements by Scott Trenda + * and Kris Kowal + * + * Accepts a date, a mask, or a date and a mask. + * Returns a formatted version of the given date. + * The date defaults to the current date/time. + * The mask defaults to dateFormat.masks.default. */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); - } - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; +(function(global) { + 'use strict'; -/** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; + var dateFormat = (function() { + var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|"[^"]*"|'[^']*'/g; + var timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g; + var timezoneClip = /[^-+\dA-Z]/g; + + // Regexes and supporting functions are cached through closure + return function (date, mask, utc, gmt) { + + // You can't provide utc if you skip other args (use the 'UTC:' mask prefix) + if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) { + mask = date; + date = undefined; + } + + date = date || new Date; + + if(!(date instanceof Date)) { + date = new Date(date); + } + + if (isNaN(date)) { + throw TypeError('Invalid date'); + } + + mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']); + + // Allow setting the utc/gmt argument via the mask + var maskSlice = mask.slice(0, 4); + if (maskSlice === 'UTC:' || maskSlice === 'GMT:') { + mask = mask.slice(4); + utc = true; + if (maskSlice === 'GMT:') { + gmt = true; + } + } + + var _ = utc ? 'getUTC' : 'get'; + var d = date[_ + 'Date'](); + var D = date[_ + 'Day'](); + var m = date[_ + 'Month'](); + var y = date[_ + 'FullYear'](); + var H = date[_ + 'Hours'](); + var M = date[_ + 'Minutes'](); + var s = date[_ + 'Seconds'](); + var L = date[_ + 'Milliseconds'](); + var o = utc ? 0 : date.getTimezoneOffset(); + var W = getWeek(date); + var N = getDayOfWeek(date); + var flags = { + d: d, + dd: pad(d), + ddd: dateFormat.i18n.dayNames[D], + dddd: dateFormat.i18n.dayNames[D + 7], + m: m + 1, + mm: pad(m + 1), + mmm: dateFormat.i18n.monthNames[m], + mmmm: dateFormat.i18n.monthNames[m + 12], + yy: String(y).slice(2), + yyyy: y, + h: H % 12 || 12, + hh: pad(H % 12 || 12), + H: H, + HH: pad(H), + M: M, + MM: pad(M), + s: s, + ss: pad(s), + l: pad(L, 3), + L: pad(Math.round(L / 10)), + t: H < 12 ? dateFormat.i18n.timeNames[0] : dateFormat.i18n.timeNames[1], + tt: H < 12 ? dateFormat.i18n.timeNames[2] : dateFormat.i18n.timeNames[3], + T: H < 12 ? dateFormat.i18n.timeNames[4] : dateFormat.i18n.timeNames[5], + TT: H < 12 ? dateFormat.i18n.timeNames[6] : dateFormat.i18n.timeNames[7], + Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''), + o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), + S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10], + W: W, + N: N + }; + + return mask.replace(token, function (match) { + if (match in flags) { + return flags[match]; + } + return match.slice(1, match.length - 1); + }); + }; + })(); -/** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} - */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; - } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; - } - return item; -}; + dateFormat.masks = { + 'default': 'ddd mmm dd yyyy HH:MM:ss', + 'shortDate': 'm/d/yy', + 'mediumDate': 'mmm d, yyyy', + 'longDate': 'mmmm d, yyyy', + 'fullDate': 'dddd, mmmm d, yyyy', + 'shortTime': 'h:MM TT', + 'mediumTime': 'h:MM:ss TT', + 'longTime': 'h:MM:ss TT Z', + 'isoDate': 'yyyy-mm-dd', + 'isoTime': 'HH:MM:ss', + 'isoDateTime': 'yyyy-mm-dd\'T\'HH:MM:sso', + 'isoUtcDateTime': 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\'', + 'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z' + }; -/** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} - */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; - } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; - } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; - } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (index < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); - } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; - } + // Internationalization strings + dateFormat.i18n = { + dayNames: [ + 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', + 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' + ], + monthNames: [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', + 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' + ], + timeNames: [ + 'a', 'p', 'am', 'pm', 'A', 'P', 'AM', 'PM' + ] + }; + +function pad(val, len) { + val = String(val); + len = len || 2; + while (val.length < len) { + val = '0' + val; } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; + return val; +} /** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. + * Get the ISO 8601 week number + * Based on comments from + * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} + * @param {Object} `date` + * @return {Number} */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; - } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); - } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); - } - } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); - } - } - return removed; - } else { - return this.remove(i, count); - } -}; +function getWeek(date) { + // Remove time components of date + var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate()); -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; + // Change date to Thursday same week + targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); -/** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; + // Take January 4th as it is always in week 1 (see ISO 8601) + var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); -/** - * Returns an array of all queue items. - * @returns {Array} - */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; + // Change date to Thursday same week + firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); -/** - * ------------- - * INTERNALS - * ------------- - */ + // Check if daylight-saving-time-switch occurred and correct for it + var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); + targetThursday.setHours(targetThursday.getHours() - ds); -/** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private - */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; + // Number of weeks between target Thursday and first Thursday + var weekDiff = (targetThursday - firstThursday) / (86400000*7); + return 1 + Math.floor(weekDiff); +} /** - * - * @param fullCopy - * @returns {Array} - * @private + * Get ISO-8601 numeric representation of the day of the week + * 1 (for Monday) through 7 (for Sunday) + * + * @param {Object} `date` + * @return {Number} */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); +function getDayOfWeek(date) { + var dow = date.getDay(); + if(dow === 0) { + dow = 7; } - return newArray; -}; + return dow; +} /** - * Grows the internal list array. - * @private + * kind-of shortcut + * @param {*} val + * @return {String} */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; +function kindOf(val) { + if (val === null) { + return 'null'; } - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; + if (val === undefined) { + return 'undefined'; + } - this._list.length *= 2; - this._capacityMask = (this._capacityMask << 1) | 1; -}; + if (typeof val !== 'object') { + return typeof val; + } -/** - * Shrinks the internal list array. - * @private - */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; + if (Array.isArray(val)) { + return 'array'; + } + + return {}.toString.call(val) + .slice(8, -1).toLowerCase(); }; -module.exports = Denque; + + if (typeof define === 'function' && define.amd) { + define(function () { + return dateFormat; + }); + } else if (true) { + module.exports = dateFormat; + } else {} +})(this); /***/ }), -/***/ 18883: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +/* eslint-env browser */ /** - * Module dependencies. + * This is the web browser implementation of `debug()`. */ -var callSiteToString = __nccwpck_require__(69829).callSiteToString -var eventListenerCount = __nccwpck_require__(69829).eventListenerCount -var relative = __nccwpck_require__(85622).relative - -/** - * Module exports. - */ +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; -module.exports = depd + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** - * Get the path to base files on. + * Colors. */ -var basePath = process.cwd() +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; /** - * Determine if namespace is contained in the string. + * 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 */ -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() - - for (var i = 0; i < vals.length; i++) { - var val = vals[i] +// eslint-disable-next-line complexity +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' || window.process.__nwjs)) { + return true; + } - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true - } - } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - return false + // 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+)/)); } /** - * Convert a data descriptor to accessor descriptor. + * Colorize log arguments if enabled. + * + * @api public */ -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value - - descriptor.get = function getter () { return value } +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } - } + if (!this.useColors) { + return; + } - delete descriptor.value - delete descriptor.writable + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - Object.defineProperty(obj, prop, descriptor) + // 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 + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - return descriptor + args.splice(lastC, 0, c); } /** - * Create arguments string to keep arity. + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public */ - -function createArgumentsString (arity) { - var str = '' - - for (var i = 0; i < arity; i++) { - str += ', arg' + i - } - - return str.substr(2) -} +exports.log = console.debug || console.log || (() => {}); /** - * Create stack string from stack. + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ - -function createStackString (stack) { - var str = this.name + ': ' + this.namespace - - if (this.message) { - str += ' deprecated ' + this.message - } - - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } - - return str +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } /** - * Create deprecate for namespace in caller. + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } - - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] - - function deprecate (message) { - // call to self as log - log.call(deprecate, message) - } - - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) - - deprecate.function = wrapfunction - deprecate.property = wrapproperty + // 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 deprecate + return r; } /** - * Determine if namespace is ignored. + * 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 isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - var str = process.env.NO_DEPRECATION || '' +module.exports = __nccwpck_require__(46243)(exports); - // namespace ignored - return containsNamespace(str, namespace) -} +const {formatters} = module.exports; /** - * Determine if namespace is traced. + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true - } +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - var str = process.env.TRACE_DEPRECATION || '' - // namespace traced - return containsNamespace(str, namespace) -} +/***/ }), + +/***/ 46243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** - * Display deprecation message. + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. */ -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - - // abort early if no destination - if (!haslisteners && this._ignored) { - return - } +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(80900); + createDebug.destroy = destroy; - var caller - var callFile - var callSite - var depSite - var i = 0 - var seen = false - var stack = getStack() - var file = this._file + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - if (site) { - // provided site - depSite = site - callSite = callSiteLocation(stack[1]) - callSite.name = depSite.name - file = callSite[0] - } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite - } + /** + * The currently active debug mode names, and names to skip. + */ - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] + createDebug.names = []; + createDebug.skips = []; - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break - } - } + /** + * 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". + */ + createDebug.formatters = {}; - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - if (key !== undefined && key in this._warned) { - // already warned - return - } + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - this._warned[key] = true + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return - } + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - // format and write message - var format = process.stderr.isTTY - ? formatColor - : formatPlain - var output = format.call(this, msg, caller, stack.slice(i)) - process.stderr.write(output + '\n', 'utf8') -} + const self = debug; -/** - * Get call site location as array. - */ + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() + args[0] = createDebug.coerce(args[0]); - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - var site = [file, line, colm] + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); - site.callSite = callSite - site.name = callSite.getFunctionName() + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - return site -} + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -/** - * Generate a default message from the site. - */ + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - // make useful anonymous name - if (!funcName) { - funcName = '' - } + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } + return debug; + } - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); -/** - * Format deprecation message without color. - */ + createDebug.names = []; + createDebug.skips = []; -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } + namespaces = split[i].replace(/\*/g, '.*?'); - return formatted - } + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } - if (caller) { - formatted += ' at ' + formatLocation(caller) - } + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } - return formatted -} + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } -/** - * Format deprecation message with color. - */ + let i; + let len; -function formatColor (msg, caller, stack) { - var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan - ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow - ' \x1b[0m' + msg + '\x1b[39m' // reset + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan - } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - return formatted - } + return false; + } - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } - return formatted + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; } +module.exports = setup; + + +/***/ }), + +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** - * Format call site location. + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); } -/** - * Get the stack as array of call sites. - */ -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace +/***/ }), - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { - // capture the stack - Error.captureStackTrace(obj) +/** + * Module dependencies. + */ - // slice this function off the top - var stack = obj.stack.slice(1) +const tty = __nccwpck_require__(33867); +const util = __nccwpck_require__(31669); - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit +/** + * This is the Node.js implementation of `debug()`. + */ - return stack -} +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); /** - * Capture call site stack from v8. + * Colors. */ -function prepareObjectStackTrace (obj, stack) { - return stack +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(59318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** - * Return a wrapped function in a deprecation message. + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - site.name = fn.name + obj[prop] = val; + return obj; +}, {}); - // eslint-disable-next-line no-eval - var deprecatedfn = eval('(function (' + args + ') {\n' + - '"use strict"\n' + - 'log.call(deprecate, message, site)\n' + - 'return fn.apply(this, arguments)\n' + - '})') +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - return deprecatedfn +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } /** - * Wrap property in a deprecation message. + * Adds ANSI color escape codes if enabled. + * + * @api public */ -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } - - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - - if (!descriptor) { - throw new TypeError('must call property on owner object') - } +function formatArgs(args) { + const {namespace: name, useColors} = this; - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} - // set site name - site.name = prop +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - var get = descriptor.get - var set = descriptor.set +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) - } - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) - } - } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - Object.defineProperty(obj, prop, descriptor) +function load() { + return process.env.DEBUG; } /** - * Create DeprecationError for deprecation + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString - - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) - - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) - - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) - - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) - - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString - } - - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val - } - }) +function init(debug) { + debug.inspectOpts = {}; - return error + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } +module.exports = __nccwpck_require__(46243)(exports); -/***/ }), - -/***/ 35554: -/***/ ((module) => { +const {formatters} = module.exports; -"use strict"; -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed +/** + * Map %o to `util.inspect()`, all on a single line. */ - +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; /** - * Module exports. + * Map %O to `util.inspect()`, allowing multiple lines if needed. */ -module.exports = callSiteToString +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; -/** - * Format a CallSite file location to a string. - */ -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' +/***/ }), - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() - } - } else { - fileName = callSite.getFileName() - } +/***/ 56323: +/***/ ((module) => { - if (fileName) { - fileLocation += fileName +"use strict"; - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } - } - } +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) +}; - return fileLocation || 'unknown source' +function isNonNullObject(value) { + return !!value && typeof value === 'object' } -/** - * Format a CallSite to a string. - */ +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); -function callSiteToString (callSite) { - var addSuffix = true - var fileLocation = callSiteFileLocation(callSite) - var functionName = callSite.getFunctionName() - var isConstructor = callSite.isConstructor() - var isMethodCall = !(callSite.isToplevel() || isConstructor) - var line = '' + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) +// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 +var canUseSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' - } +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE +} - line += functionName +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } - } else { - line += typeName + '.' + (methodName || '') - } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value +} - if (addSuffix) { - line += ' (' + fileLocation + ')' - } +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) +} - return line +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge + } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge } -/** - * Get constructor name of reviver. - */ +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return target.propertyIsEnumerable(symbol) + }) + : [] +} -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) } +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false + } +} -/***/ }), +// Protects from prototype poisoning and unexpected merging up the prototype chain. +function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, + && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, + && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +} -/***/ 12078: -/***/ ((module) => { +function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return + } -"use strict"; -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination +} +function deepmerge(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() + // implementations can use it. The caller may not replace it. + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; -/** - * Module exports. - * @public - */ + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) + } +} -module.exports = eventListenerCount +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') + } -/** - * Get the count of listeners on an event emitter of a specific type. - */ + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) +}; -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length -} +var deepmerge_1 = deepmerge; + +module.exports = deepmerge_1; /***/ }), -/***/ 69829: +/***/ 18611: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ +var Stream = __nccwpck_require__(92413).Stream; +var util = __nccwpck_require__(31669); -var EventEmitter = __nccwpck_require__(28614).EventEmitter +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; -/** - * Module exports. - * @public - */ + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace +DelayedStream.create = function(source, options) { + var delayedStream = new this(); - function prepareObjectStackTrace (obj, stack) { - return stack + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 - - // capture the stack - Error.captureStackTrace(obj) - - // slice the stack - var stack = obj.stack.slice() - - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - - return stack[0].toString ? toString : __nccwpck_require__(35554) -}) - -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __nccwpck_require__(12078) -}) - -/** - * Define a lazy property. - */ - -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() + delayedStream.source = source; - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; - return val + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); } - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) -} + return delayedStream; +}; -/** - * Call toString() on the obj - */ +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); -function toString (obj) { - return obj.toString() -} +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } -/***/ }), + this.source.resume(); +}; -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; -"use strict"; +DelayedStream.prototype.release = function() { + this._released = true; + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } - /* istanbul ignore next */ + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + this._bufferedEvents.push(args); +}; - this.name = 'Deprecation'; +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; } -} + if (this.dataSize <= this.maxDataSize) { + return; + } -exports.Deprecation = Deprecation; + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; /***/ }), -/***/ 43225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 42342: +/***/ ((module) => { "use strict"; -/*! - * destroy - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - /** - * Module dependencies. - * @private + * Custom implementation of a double ended queue. */ - -var ReadStream = __nccwpck_require__(35747).ReadStream -var Stream = __nccwpck_require__(92413) +function Denque(array) { + this._head = 0; + this._tail = 0; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } +} /** - * Module exports. - * @public + * ------------- + * PUBLIC API + * ------------- */ -module.exports = destroy - /** - * Destroy a stream. - * - * @param {object} stream - * @public + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} */ - -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } - - if (!(stream instanceof Stream)) { - return stream - } - - if (typeof stream.destroy === 'function') { - stream.destroy() +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; } - - return stream -} + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; /** - * Destroy a ReadStream. - * - * @param {object} stream - * @private + * Alias for peakAt() + * @param i + * @returns {*} */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; -function destroyReadStream(stream) { - stream.destroy() - - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) - } +/** + * Returns the first item in the list without removing it. + * @returns {*} + */ +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; - return stream -} +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; /** - * On open handler to close stream. - * @private + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) */ +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); } -} +}); +/** + * Return the number of items on the list, or 0 if empty. + * @returns {number} + */ +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; -/***/ }), +/** + * Add an item at the beginning of the list. + * @param item + */ +Denque.prototype.unshift = function unshift(item) { + if (item === undefined) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; -/***/ 12437: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; -/* @flow */ -/*:: +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (item === undefined) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); + } -type DotenvParseOptions = { - debug?: boolean -} + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; -// keys and values from src -type DotenvParseOutput = { [string]: string } +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; +}; -type DotenvConfigOptions = { - path?: string, // path to .env file - encoding?: string, // encoding of .env file - debug?: string // turn on logging for debugging purposes -} +/** + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} + */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; -type DotenvConfigOutput = { - parsed?: DotenvParseOutput, - error?: Error -} +/** + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} + */ +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); + } + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; +}; -*/ +/** + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. + * + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} + */ +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; + } + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); + } + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } +}; -const fs = __nccwpck_require__(35747) -const path = __nccwpck_require__(85622) +/** + * Soft clear - does not reset capacity. + */ +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; -function log (message /*: string */) { - console.log(`[dotenv][DEBUG] ${message}`) -} +/** + * Returns true or false whether the list is empty. + * @returns {boolean} + */ +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; -const NEWLINE = '\n' -const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ -const RE_NEWLINES = /\\n/g -const NEWLINES_MATCH = /\n|\r|\r\n/ +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; -// Parses src into an Object -function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { - const debug = Boolean(options && options.debug) - const obj = {} +/** + * ------------- + * INTERNALS + * ------------- + */ - // convert Buffers before splitting into lines and processing - src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { - // matching "KEY' and 'VAL' in 'KEY=VAL' - const keyValueArr = line.match(RE_INI_KEY_VAL) - // matched? - if (keyValueArr != null) { - const key = keyValueArr[1] - // default undefined or missing values to empty string - let val = (keyValueArr[2] || '') - const end = val.length - 1 - const isDoubleQuoted = val[0] === '"' && val[end] === '"' - const isSingleQuoted = val[0] === "'" && val[end] === "'" +/** + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private + */ +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); +}; - // if single or double quoted, remove quotes - if (isSingleQuoted || isDoubleQuoted) { - val = val.substring(1, end) +/** + * + * @param fullCopy + * @returns {Array} + * @private + */ +Denque.prototype._copyArray = function _copyArray(fullCopy) { + var newArray = []; + var list = this._list; + var len = list.length; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < len; i++) newArray.push(list[i]); + for (i = 0; i < this._tail; i++) newArray.push(list[i]); + } else { + for (i = this._head; i < this._tail; i++) newArray.push(list[i]); + } + return newArray; +}; - // if double quoted, expand newlines - if (isDoubleQuoted) { - val = val.replace(RE_NEWLINES, NEWLINE) - } - } else { - // remove surrounding whitespace - val = val.trim() - } +/** + * Grows the internal list array. + * @private + */ +Denque.prototype._growArray = function _growArray() { + if (this._head) { + // copy existing data, head to end, then beginning to tail. + this._list = this._copyArray(true); + this._head = 0; + } - obj[key] = val - } else if (debug) { - log(`did not match key and value when parsing line ${idx + 1}: ${line}`) - } - }) + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; - return obj -} + this._list.length *= 2; + this._capacityMask = (this._capacityMask << 1) | 1; +}; -// Populates process.env from .env file -function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { - let dotenvPath = path.resolve(process.cwd(), '.env') - let encoding /*: string */ = 'utf8' - let debug = false +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; - if (options) { - if (options.path != null) { - dotenvPath = options.path - } - if (options.encoding != null) { - encoding = options.encoding - } - if (options.debug != null) { - debug = true - } - } - try { - // specifying an encoding returns a string instead of a buffer - const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) +module.exports = Denque; - Object.keys(parsed).forEach(function (key) { - if (!Object.prototype.hasOwnProperty.call(process.env, key)) { - process.env[key] = parsed[key] - } else if (debug) { - log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) - } - }) - return { parsed } - } catch (e) { - return { error: e } - } -} +/***/ }), -module.exports.config = config -module.exports.parse = parse +/***/ 18883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), +/** + * Module dependencies. + */ -/***/ 11728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var callSiteToString = __nccwpck_require__(69829).callSiteToString +var eventListenerCount = __nccwpck_require__(69829).eventListenerCount +var relative = __nccwpck_require__(85622).relative -"use strict"; +/** + * Module exports. + */ +module.exports = depd -var Buffer = __nccwpck_require__(21867).Buffer; +/** + * Get the path to base files on. + */ -var getParamBytesForAlg = __nccwpck_require__(30528); +var basePath = process.cwd() -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); +/** + * Determine if namespace is contained in the string. + */ -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } + for (var i = 0; i < vals.length; i++) { + var val = vals[i] - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); -} + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); + return false +} - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; +/** + * Convert a data descriptor to accessor descriptor. + */ - var inputLength = signature.length; +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } + descriptor.get = function getter () { return value } - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } + delete descriptor.value + delete descriptor.writable - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } + Object.defineProperty(obj, prop, descriptor) - var rLength = signature[offset++]; + return descriptor +} - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } +/** + * Create arguments string to keep arity. + */ - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } +function createArgumentsString (arity) { + var str = '' - var rOffset = offset; - offset += rLength; + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } + return str.substr(2) +} - var sLength = signature[offset++]; +/** + * Create stack string from stack. + */ - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } +function createStackString (stack) { + var str = this.name + ': ' + this.namespace - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + if (this.message) { + str += ' deprecated ' + this.message + } - var sOffset = offset; - offset += sLength; + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } + return str +} - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; +/** + * Create deprecate for namespace in caller. + */ - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] - offset = paramBytes; + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) - dst = dst.toString('base64'); - dst = base64Url(dst); + deprecate.function = wrapfunction + deprecate.property = wrapproperty - return dst; + return deprecate } -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } +/** + * Determine if namespace is ignored. + */ - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } - return padding; -} + var str = process.env.NO_DEPRECATION || '' -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); + // namespace ignored + return containsNamespace(str, namespace) +} - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } +/** + * Determine if namespace is traced. + */ - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + var str = process.env.TRACE_DEPRECATION || '' - var shortLength = rsBytes < MAX_OCTET; + // namespace traced + return containsNamespace(str, namespace) +} - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); +/** + * Display deprecation message. + */ - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - return dst; -} + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer -}; + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } -/***/ }), + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] -/***/ 30528: -/***/ ((module) => { + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } -"use strict"; + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + if (key !== undefined && key in this._warned) { + // already warned + return + } -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} + this._warned[key] = true -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } - throw new Error('Unknown algorithm "' + alg + '"'); + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') } -module.exports = getParamBytesForAlg; - +/** + * Get call site location as array. + */ -/***/ }), +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() -/***/ 14401: -/***/ ((module) => { + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } -"use strict"; -/*! - * ee-first - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ + var site = [file, line, colm] + site.callSite = callSite + site.name = callSite.getFunctionName() + return site +} /** - * Module exports. - * @public + * Generate a default message from the site. */ -module.exports = first - -/** - * Get the first event in a set of event emitters and event pairs. - * - * @param {array} stuff - * @param {function} done - * @public - */ +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') + // make useful anonymous name + if (!funcName) { + funcName = '' + } - var cleanups = [] + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } - var ee = arr[0] + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) +/** + * Format deprecation message without color. + */ - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() - function callback() { - cleanup() - done.apply(null, arguments) - } + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) } - } - function thunk(fn) { - done = fn + return formatted } - thunk.cancel = cleanup + if (caller) { + formatted += ' at ' + formatLocation(caller) + } - return thunk + return formatted } /** - * Create the event listener. - * @private + * Format deprecation message with color. */ -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan } - done(err, ee, event, args) + return formatted } -} + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } -/***/ }), - -/***/ 18212: -/***/ ((module) => { + return formatted +} -"use strict"; +/** + * Format call site location. + */ +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; -}; +/** + * Get the stack as array of call sites. + */ +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace -/***/ }), + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) -/***/ 16592: -/***/ ((module) => { + // capture the stack + Error.captureStackTrace(obj) -"use strict"; -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ + // slice this function off the top + var stack = obj.stack.slice(1) + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + return stack +} /** - * Module exports. - * @public + * Capture call site stack from v8. */ -module.exports = encodeUrl +function prepareObjectStackTrace (obj, stack) { + return stack +} /** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private + * Return a wrapped function in a deprecation message. */ -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } -/** - * RegExp to match unmatched surrogate pair. - * @private - */ + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + site.name = fn.name -/** - * String to replace unmatched surrogate pair with. - * @private - */ + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + return deprecatedfn +} /** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). - * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. - * - * @param {string} url - * @return {string} - * @public + * Wrap property in a deprecation message. */ -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} - - -/***/ }), - -/***/ 23505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var util = __nccwpck_require__(31669); -var isArrayish = __nccwpck_require__(7604); - -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } - - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } - - message = message instanceof Error - ? message.message - : (message || this.message); - - Error.call(this, message); - Error.captureStackTrace(this, errorExError); - - this.name = name; - - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); - - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } - - var modifier = properties[key]; - - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } - - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); - - var overwrittenStack = null; +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - stackDescriptor.set = function (newstack) { - overwrittenStack = newstack; - }; + if (!descriptor) { + throw new TypeError('must call property on owner object') + } - stackDescriptor.get = function () { - var stack = (overwrittenStack || ((stackGetter) - ? stackGetter.call(this) - : stackValue)).split(/\r?\n+/g); + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } - // starting in Node 7, the stack builder caches the message. - // just replace it. - if (!overwrittenStack) { - stack[0] = this.name + ': ' + this.message; - } + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + // set site name + site.name = prop - var modifier = properties[key]; + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } + var get = descriptor.get + var set = descriptor.set - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } - return stack.join('\n'); - }; + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } - Object.defineProperty(this, 'stack', stackDescriptor); - }; + Object.defineProperty(obj, prop, descriptor) +} - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } +/** + * Create DeprecationError for deprecation + */ - return errorExError; -}; +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) - return message; - } - }; -}; + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) - if (v) { - return str.replace('%s', v.toString()); - } + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } - return null; - } - }; -}; + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) -module.exports = errorEx; + return error +} /***/ }), -/***/ 94070: +/***/ 35554: /***/ ((module) => { "use strict"; /*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu + * depd + * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ -/** - * Module variables. - * @private - */ - -var matchHtmlRegExp = /["'&<>]/; - /** * Module exports. - * @public */ -module.exports = escapeHtml; +module.exports = callSiteToString /** - * Escape special characters in the given string of html. - * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public + * Format a CallSite file location to a string. */ -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' - if (!match) { - return str; + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() } - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; + if (fileName) { + fileLocation += fileName - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 39: // ' - escape = '''; - break; - case 60: // < - escape = '<'; - break; - case 62: // > - escape = '>'; - break; - default: - continue; - } + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber - if (lastIndex !== index) { - html += str.substring(lastIndex, index); + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } } - - lastIndex = index + 1; - html += escape; } - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; + return fileLocation || 'unknown source' } +/** + * Format a CallSite to a string. + */ -/***/ }), +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' -/***/ 98691: -/***/ ((module) => { + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) -"use strict"; + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + line += functionName -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } - // Escape characters with special meaning either inside or outside character sets. - // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. - return string - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d'); -}; + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} /***/ }), -/***/ 69972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 12078: +/***/ ((module) => { "use strict"; /*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson + * depd + * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ @@ -43230,2006 +43648,1607 @@ module.exports = string => { * @public */ -module.exports = etag +module.exports = eventListenerCount /** - * Module dependencies. - * @private + * Get the count of listeners on an event emitter of a specific type. */ -var crypto = __nccwpck_require__(76417) -var Stats = __nccwpck_require__(35747).Stats +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} -/** - * Module variables. - * @private - */ -var toString = Object.prototype.toString +/***/ }), -/** - * Generate an entity tag. - * - * @param {Buffer|string} entity - * @return {string} - * @private +/***/ 69829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' - } - // compute hash of entity - var hash = crypto - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27) - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length +/** + * Module dependencies. + * @private + */ - return '"' + len.toString(16) + '-' + hash + '"' -} +var EventEmitter = __nccwpck_require__(28614).EventEmitter /** - * Create a simple ETag. - * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} + * Module exports. * @public */ -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace (obj, stack) { + return stack } - // support fs.Stats object - var isStats = isstats(entity) - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') - } + // capture the stack + Error.captureStackTrace(obj) - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) + // slice the stack + var stack = obj.stack.slice() - return weak - ? 'W/' + tag - : tag -} + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : __nccwpck_require__(35554) +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || __nccwpck_require__(12078) +}) /** - * Determine if object is a Stats object. - * - * @param {object} obj - * @return {boolean} - * @api private + * Define a lazy property. */ -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val } - // quack quack - return obj && typeof obj === 'object' && - 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && - 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && - 'ino' in obj && typeof obj.ino === 'number' && - 'size' in obj && typeof obj.size === 'number' + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) } /** - * Generate a tag for a stat. - * - * @param {object} stat - * @return {string} - * @private + * Call toString() on the obj */ -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) +function toString (obj) { + return obj.toString() +} + + +/***/ }), + +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } - return '"' + size + '-' + mtime + '"' } +exports.Deprecation = Deprecation; + /***/ }), -/***/ 68883: +/***/ 43225: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var original = __nccwpck_require__(80086) -var parse = __nccwpck_require__(78835).parse -var events = __nccwpck_require__(28614) -var https = __nccwpck_require__(57211) -var http = __nccwpck_require__(98605) -var util = __nccwpck_require__(31669) +"use strict"; +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ -var httpsOptions = [ - 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', - 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' -] -var bom = [239, 187, 191] -var colon = 58 -var space = 32 -var lineFeed = 10 -var carriageReturn = 13 -function hasBom (buf) { - return bom.every(function (charCode, index) { - return buf[index] === charCode - }) -} +/** + * Module dependencies. + * @private + */ + +var ReadStream = __nccwpck_require__(35747).ReadStream +var Stream = __nccwpck_require__(92413) /** - * Creates a new EventSource object - * - * @param {String} url the URL to which to connect - * @param {Object} [eventSourceInitDict] extra init params. See README for details. - * @api public - **/ -function EventSource (url, eventSourceInitDict) { - var readyState = EventSource.CONNECTING - Object.defineProperty(this, 'readyState', { - get: function () { - return readyState - } - }) + * Module exports. + * @public + */ - Object.defineProperty(this, 'url', { - get: function () { - return url - } - }) +module.exports = destroy - var self = this - self.reconnectInterval = 1000 +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ - function onConnectionClosed (message) { - if (readyState === EventSource.CLOSED) return - readyState = EventSource.CONNECTING - _emit('error', new Event('error', {message: message})) +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } - // The url may have been changed by a temporary - // redirect. If that's the case, revert it now. - if (reconnectUrl) { - url = reconnectUrl - reconnectUrl = null - } - setTimeout(function () { - if (readyState !== EventSource.CONNECTING) { - return - } - connect() - }, self.reconnectInterval) + if (!(stream instanceof Stream)) { + return stream } - var req - var lastEventId = '' - if (eventSourceInitDict && eventSourceInitDict.headers && eventSourceInitDict.headers['Last-Event-ID']) { - lastEventId = eventSourceInitDict.headers['Last-Event-ID'] - delete eventSourceInitDict.headers['Last-Event-ID'] + if (typeof stream.destroy === 'function') { + stream.destroy() } - var discardTrailingNewline = false - var data = '' - var eventName = '' + return stream +} - var reconnectUrl = null +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ - function connect () { - var options = parse(url) - var isSecure = options.protocol === 'https:' - options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } - if (lastEventId) options.headers['Last-Event-ID'] = lastEventId - if (eventSourceInitDict && eventSourceInitDict.headers) { - for (var i in eventSourceInitDict.headers) { - var header = eventSourceInitDict.headers[i] - if (header) { - options.headers[i] = header - } - } - } +function destroyReadStream(stream) { + stream.destroy() - // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, - // but for now exists as a backwards-compatibility layer - options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } - // If specify http proxy, make the request to sent to the proxy server, - // and include the original url in path and Host headers - var useProxy = eventSourceInitDict && eventSourceInitDict.proxy - if (useProxy) { - var proxy = parse(eventSourceInitDict.proxy) - isSecure = proxy.protocol === 'https:' + return stream +} - options.protocol = isSecure ? 'https:' : 'http:' - options.path = url - options.headers.Host = options.host - options.hostname = proxy.hostname - options.host = proxy.host - options.port = proxy.port - } +/** + * On open handler to close stream. + * @private + */ - // If https options are specified, merge them into the request options - if (eventSourceInitDict && eventSourceInitDict.https) { - for (var optName in eventSourceInitDict.https) { - if (httpsOptions.indexOf(optName) === -1) { - continue - } +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} - var option = eventSourceInitDict.https[optName] - if (option !== undefined) { - options[optName] = option - } - } - } - // Pass this on to the XHR - if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { - options.withCredentials = eventSourceInitDict.withCredentials - } +/***/ }), - req = (isSecure ? https : http).request(options, function (res) { - // Handle HTTP errors - if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { - _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) - onConnectionClosed() - return - } +/***/ 12437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Handle HTTP redirects - if (res.statusCode === 301 || res.statusCode === 307) { - if (!res.headers.location) { - // Server sent redirect response without Location header. - _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) - return - } - if (res.statusCode === 307) reconnectUrl = url - url = res.headers.location - process.nextTick(connect) - return - } +/* @flow */ +/*:: - if (res.statusCode !== 200) { - _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) - return self.close() - } +type DotenvParseOptions = { + debug?: boolean +} - readyState = EventSource.OPEN - res.on('close', function () { - res.removeAllListeners('close') - res.removeAllListeners('end') - onConnectionClosed() - }) +// keys and values from src +type DotenvParseOutput = { [string]: string } - res.on('end', function () { - res.removeAllListeners('close') - res.removeAllListeners('end') - onConnectionClosed() - }) - _emit('open', new Event('open')) +type DotenvConfigOptions = { + path?: string, // path to .env file + encoding?: string, // encoding of .env file + debug?: string // turn on logging for debugging purposes +} - // text/event-stream parser adapted from webkit's - // Source/WebCore/page/EventSource.cpp - var isFirst = true - var buf - res.on('data', function (chunk) { - buf = buf ? Buffer.concat([buf, chunk]) : chunk - if (isFirst && hasBom(buf)) { - buf = buf.slice(bom.length) - } +type DotenvConfigOutput = { + parsed?: DotenvParseOutput, + error?: Error +} - isFirst = false - var pos = 0 - var length = buf.length +*/ - while (pos < length) { - if (discardTrailingNewline) { - if (buf[pos] === lineFeed) { - ++pos - } - discardTrailingNewline = false - } +const fs = __nccwpck_require__(35747) +const path = __nccwpck_require__(85622) - var lineLength = -1 - var fieldLength = -1 - var c +function log (message /*: string */) { + console.log(`[dotenv][DEBUG] ${message}`) +} - for (var i = pos; lineLength < 0 && i < length; ++i) { - c = buf[i] - if (c === colon) { - if (fieldLength < 0) { - fieldLength = i - pos - } - } else if (c === carriageReturn) { - discardTrailingNewline = true - lineLength = i - pos - } else if (c === lineFeed) { - lineLength = i - pos - } - } +const NEWLINE = '\n' +const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ +const RE_NEWLINES = /\\n/g +const NEWLINES_MATCH = /\n|\r|\r\n/ - if (lineLength < 0) { - break - } +// Parses src into an Object +function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { + const debug = Boolean(options && options.debug) + const obj = {} - parseEventStreamLine(buf, pos, fieldLength, lineLength) + // convert Buffers before splitting into lines and processing + src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { + // matching "KEY' and 'VAL' in 'KEY=VAL' + const keyValueArr = line.match(RE_INI_KEY_VAL) + // matched? + if (keyValueArr != null) { + const key = keyValueArr[1] + // default undefined or missing values to empty string + let val = (keyValueArr[2] || '') + const end = val.length - 1 + const isDoubleQuoted = val[0] === '"' && val[end] === '"' + const isSingleQuoted = val[0] === "'" && val[end] === "'" - pos += lineLength + 1 - } + // if single or double quoted, remove quotes + if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) - if (pos === length) { - buf = void 0 - } else if (pos > 0) { - buf = buf.slice(pos) + // if double quoted, expand newlines + if (isDoubleQuoted) { + val = val.replace(RE_NEWLINES, NEWLINE) } - }) - }) + } else { + // remove surrounding whitespace + val = val.trim() + } - req.on('error', function (err) { - onConnectionClosed(err.message) - }) + obj[key] = val + } else if (debug) { + log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + } + }) - if (req.setNoDelay) req.setNoDelay(true) - req.end() - } + return obj +} - connect() +// Populates process.env from .env file +function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { + let dotenvPath = path.resolve(process.cwd(), '.env') + let encoding /*: string */ = 'utf8' + let debug = false - function _emit () { - if (self.listeners(arguments[0]).length > 0) { - self.emit.apply(self, arguments) + if (options) { + if (options.path != null) { + dotenvPath = options.path + } + if (options.encoding != null) { + encoding = options.encoding + } + if (options.debug != null) { + debug = true } } - this._close = function () { - if (readyState === EventSource.CLOSED) return - readyState = EventSource.CLOSED - if (req.abort) req.abort() - if (req.xhr && req.xhr.abort) req.xhr.abort() - } - - function parseEventStreamLine (buf, pos, fieldLength, lineLength) { - if (lineLength === 0) { - if (data.length > 0) { - var type = eventName || 'message' - _emit(type, new MessageEvent(type, { - data: data.slice(0, -1), // remove trailing newline - lastEventId: lastEventId, - origin: original(url) - })) - data = '' - } - eventName = void 0 - } else if (fieldLength > 0) { - var noValue = fieldLength < 0 - var step = 0 - var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() + try { + // specifying an encoding returns a string instead of a buffer + const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) - if (noValue) { - step = lineLength - } else if (buf[pos + fieldLength + 1] !== space) { - step = fieldLength + 1 - } else { - step = fieldLength + 2 + Object.keys(parsed).forEach(function (key) { + if (!Object.prototype.hasOwnProperty.call(process.env, key)) { + process.env[key] = parsed[key] + } else if (debug) { + log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) } - pos += step - - var valueLength = lineLength - step - var value = buf.slice(pos, pos + valueLength).toString() + }) - if (field === 'data') { - data += value + '\n' - } else if (field === 'event') { - eventName = value - } else if (field === 'id') { - lastEventId = value - } else if (field === 'retry') { - var retry = parseInt(value, 10) - if (!Number.isNaN(retry)) { - self.reconnectInterval = retry - } - } - } + return { parsed } + } catch (e) { + return { error: e } } } -module.exports = EventSource +module.exports.config = config +module.exports.parse = parse -util.inherits(EventSource, events.EventEmitter) -EventSource.prototype.constructor = EventSource; // make stacktraces readable -['open', 'error', 'message'].forEach(function (method) { - Object.defineProperty(EventSource.prototype, 'on' + method, { - /** - * Returns the current listener - * - * @return {Mixed} the set function or undefined - * @api private - */ - get: function get () { - var listener = this.listeners(method)[0] - return listener ? (listener._listener ? listener._listener : listener) : undefined - }, +/***/ }), - /** - * Start listening for events - * - * @param {Function} listener the listener - * @return {Mixed} the set function or undefined - * @api private - */ - set: function set (listener) { - this.removeAllListeners(method) - this.addEventListener(method, listener) - } - }) -}) +/***/ 11728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Ready states - */ -Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) -Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) -Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) +"use strict"; -EventSource.prototype.CONNECTING = 0 -EventSource.prototype.OPEN = 1 -EventSource.prototype.CLOSED = 2 -/** - * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close - * @api public - */ -EventSource.prototype.close = function () { - this._close() -} +var Buffer = __nccwpck_require__(21867).Buffer; -/** - * Emulates the W3C Browser based WebSocket interface using addEventListener. - * - * @param {String} type A string representing the event type to listen out for - * @param {Function} listener callback - * @see https://developer.mozilla.org/en/DOM/element.addEventListener - * @see http://dev.w3.org/html5/websockets/#the-websocket-interface - * @api public - */ -EventSource.prototype.addEventListener = function addEventListener (type, listener) { - if (typeof listener === 'function') { - // store a reference so we can return the original function again - listener._listener = listener - this.on(type, listener) - } -} +var getParamBytesForAlg = __nccwpck_require__(30528); -/** - * Emulates the W3C Browser based WebSocket interface using dispatchEvent. - * - * @param {Event} event An event to be dispatched - * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent - * @api public - */ -EventSource.prototype.dispatchEvent = function dispatchEvent (event) { - if (!event.type) { - throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') - } - // if event is instance of an CustomEvent (or has 'details' property), - // send the detail object as the payload for the event - this.emit(event.type, event.detail) -} +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); -/** - * Emulates the W3C Browser based WebSocket interface using removeEventListener. - * - * @param {String} type A string representing the event type to remove - * @param {Function} listener callback - * @see https://developer.mozilla.org/en/DOM/element.removeEventListener - * @see http://dev.w3.org/html5/websockets/#the-websocket-interface - * @api public - */ -EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { - if (typeof listener === 'function') { - listener._listener = undefined - this.removeListener(type, listener) - } +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); } -/** - * W3C Event - * - * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event - * @api private - */ -function Event (type, optionalProperties) { - Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) - if (optionalProperties) { - for (var f in optionalProperties) { - if (optionalProperties.hasOwnProperty(f)) { - Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) - } - } - } -} +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } -/** - * W3C MessageEvent - * - * @see http://www.w3.org/TR/webmessaging/#event-definitions - * @api private - */ -function MessageEvent (type, eventInitDict) { - Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) - for (var f in eventInitDict) { - if (eventInitDict.hasOwnProperty(f)) { - Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) - } - } + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); } +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); -/***/ }), + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; -/***/ 71204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var inputLength = signature.length; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } -module.exports = __nccwpck_require__(22587); + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + var rLength = signature[offset++]; -/***/ }), + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } -/***/ 313: -/***/ ((module, exports, __nccwpck_require__) => { + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + var rOffset = offset; + offset += rLength; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + var sLength = signature[offset++]; -/** - * Module dependencies. - * @private - */ + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } -var finalhandler = __nccwpck_require__(30810); -var Router = __nccwpck_require__(24963); -var methods = __nccwpck_require__(58752); -var middleware = __nccwpck_require__(92636); -var query = __nccwpck_require__(79768); -var debug = __nccwpck_require__(52529)('express:application'); -var View = __nccwpck_require__(99209); -var http = __nccwpck_require__(98605); -var compileETag = __nccwpck_require__(53561).compileETag; -var compileQueryParser = __nccwpck_require__(53561).compileQueryParser; -var compileTrust = __nccwpck_require__(53561).compileTrust; -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var merge = __nccwpck_require__(44429); -var resolve = __nccwpck_require__(85622).resolve; -var setPrototypeOf = __nccwpck_require__(40414) -var slice = Array.prototype.slice; + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } -/** - * Application prototype. - */ + var sOffset = offset; + offset += sLength; -var app = exports = module.exports = {}; + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } -/** - * Variable for trust proxy inheritance back-compat - * @private - */ + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); -/** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - * - * @private - */ + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; + offset = paramBytes; - this.defaultConfiguration(); -}; + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); -/** - * Initialize application configuration. - * @private - */ + dst = dst.toString('base64'); + dst = base64Url(dst); -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; + return dst; +} - // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); - this.set('query parser', 'extended'); - this.set('subdomain offset', 2); - this.set('trust proxy', false); +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } - debug('booting in %s mode', env); + return padding; +} - this.on('mount', function onmount(parent) { - // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; - } +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } - // setup locals - this.locals = Object.create(null); + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; - // top-most app is mounted at / - this.mountpath = '/'; + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; - // default locals - this.locals.settings = this.settings; + var shortLength = rsBytes < MAX_OCTET; - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - if (env === 'production') { - this.enable('view cache'); - } + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } - Object.defineProperty(this, 'router', { - get: function() { - throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); - } - }); + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer }; -/** - * lazily adds the base router if it has not yet been added. - * - * We cannot add the base router in the defaultConfiguration because - * it reads app settings which might be set after that has run. - * - * @private - */ -app.lazyrouter = function lazyrouter() { - if (!this._router) { - this._router = new Router({ - caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') - }); - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); - } +/***/ }), + +/***/ 30528: +/***/ ((module) => { + +"use strict"; + + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) }; -/** - * Dispatch a req, res pair into the application. Starts pipeline processing. - * - * If no callback is provided, then default error handlers will respond - * in the event of an error bubbling through the stack. - * - * @private +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); +} + +module.exports = getParamBytesForAlg; + + +/***/ }), + +/***/ 14401: +/***/ ((module) => { + +"use strict"; +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed */ -app.handle = function handle(req, res, callback) { - var router = this._router; - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; - } +/** + * Module exports. + * @public + */ - router.handle(req, res, done); -}; +module.exports = first /** - * Proxy `Router#use()` to add middleware to the app router. - * See Router#use() documentation for details. - * - * If the _fn_ parameter is an express app, then it will be - * mounted at the _route_ specified. + * Get the first event in a set of event emitters and event pairs. * + * @param {array} stuff + * @param {function} done * @public */ -app.use = function use(fn) { - var offset = 0; - var path = '/'; +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; + var cleanups = [] - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) } } - var fns = flatten(slice.call(arguments, offset)); + function callback() { + cleanup() + done.apply(null, arguments) + } - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } } - // setup router - this.lazyrouter(); - var router = this._router; + function thunk(fn) { + done = fn + } - fns.forEach(function (fn) { - // non-express app - if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); - } + thunk.cancel = cleanup - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; - - // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { - setPrototypeOf(req, orig.request) - setPrototypeOf(res, orig.response) - next(err); - }); - }); - - // mounted an app - fn.emit('mount', this); - }, this); - - return this; -}; + return thunk +} /** - * Proxy to the app `Router#route()` - * Returns a new `Route` instance for the _path_. - * - * Routes are isolated middleware stacks for specific paths. - * See the Route api docs for details. - * - * @public + * Create the event listener. + * @private */ -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null -/** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.ejs" file Express will invoke the following internally: - * - * app.engine('ejs', require('ejs').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/tj/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining - * @public - */ + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); + done(err, ee, event, args) } +} - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; - // store engine - this.engines[extension] = fn; +/***/ }), - return this; -}; +/***/ 18212: +/***/ ((module) => { -/** - * Proxy to `Router#param()` with one added api feature. The _name_ parameter - * can be an array of names. - * - * See the Router#param() docs for more details. - * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining - * @public - */ +"use strict"; -app.param = function param(name, fn) { - this.lazyrouter(); - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); - } +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; - return this; - } - this._router.param(name, fn); +/***/ }), - return this; -}; +/***/ 16592: +/***/ ((module) => { -/** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.set('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param {String} setting - * @param {*} [val] - * @return {Server} for chaining - * @public +"use strict"; +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed */ -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; - } - - debug('set "%s" to %o', setting, val); - // set value - this.settings[setting] = val; - // trigger matched settings - switch (setting) { - case 'etag': - this.set('etag fn', compileETag(val)); - break; - case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; - case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); +/** + * Module exports. + * @public + */ - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); +module.exports = encodeUrl - break; - } +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ - return this; -}; +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - * - * @return {String} + * RegExp to match unmatched surrogate pair. * @private */ -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; -}; +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @public + * String to replace unmatched surrogate pair with. + * @private */ -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' /** - * Check if `setting` is disabled. + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. * - * app.disabled('foo') - * // => true + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). * - * app.enable('foo') - * app.disabled('foo') - * // => false + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. * - * @param {String} setting - * @return {Boolean} + * @param {string} url + * @return {string} * @public */ -app.disabled = function disabled(setting) { - return !this.set(setting); -}; - -/** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} -app.enable = function enable(setting) { - return this.set(setting, true); -}; -/** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ +/***/ }), -app.disable = function disable(setting) { - return this.set(setting, false); -}; +/***/ 23505: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ +"use strict"; -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); - } - this.lazyrouter(); +var util = __nccwpck_require__(31669); +var isArrayish = __nccwpck_require__(7604); - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } -/** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining - * @public - */ + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } -app.all = function all(path) { - this.lazyrouter(); + message = message instanceof Error + ? message.message + : (message || this.message); - var route = this._router.route(path); - var args = slice.call(arguments, 1); + Error.call(this, message); + Error.captureStackTrace(this, errorExError); - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); - } + this.name = name; - return this; -}; + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); -// del -> delete alias + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + var modifier = properties[key]; -/** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback - * @public - */ + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var renderOptions = {}; - var view; + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + var overwrittenStack = null; - // merge app.locals - merge(renderOptions, this.locals); + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } + stackDescriptor.set = function (newstack) { + overwrittenStack = newstack; + }; - // merge options - merge(renderOptions, opts); + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } + // starting in Node 7, the stack builder caches the message. + // just replace it. + if (!overwrittenStack) { + stack[0] = this.name + ': ' + this.message; + } - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } - // view - if (!view) { - var View = this.get('view'); + var modifier = properties[key]; - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); - } + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } - // prime the cache - if (renderOptions.cache) { - cache[name] = view; - } - } + return stack.join('\n'); + }; - // render - tryRender(view, renderOptions, done); -}; + Object.defineProperty(this, 'stack', stackDescriptor); + }; -/** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - * - * @return {http.Server} - * @public - */ + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util.inherits(errorExError, Error); + } -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); + return errorExError; }; -/** - * Log error using console.error. - * - * @param {Error} err - * @private - */ +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } -/** - * Try rendering a view. - * @private - */ + return message; + } + }; +}; -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } -} +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; + + if (v) { + return str.replace('%s', v.toString()); + } + + return null; + } + }; +}; + +module.exports = errorEx; /***/ }), -/***/ 22587: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 94070: +/***/ ((module) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu * MIT Licensed */ /** - * Module dependencies. + * Module variables. + * @private */ -var bodyParser = __nccwpck_require__(97076) -var EventEmitter = __nccwpck_require__(28614).EventEmitter; -var mixin = __nccwpck_require__(11149); -var proto = __nccwpck_require__(313); -var Route = __nccwpck_require__(23699); -var Router = __nccwpck_require__(24963); -var req = __nccwpck_require__(71260); -var res = __nccwpck_require__(64934); +var matchHtmlRegExp = /["'&<>]/; /** - * Expose `createApplication()`. + * Module exports. + * @public */ -exports = module.exports = createApplication; +module.exports = escapeHtml; /** - * Create an express application. + * Escape special characters in the given string of html. * - * @return {Function} - * @api public - */ - -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; - - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); - - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - app.init(); - return app; -} - -/** - * Expose the prototypes. + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public */ -exports.application = proto; -exports.request = req; -exports.response = res; - -/** - * Expose constructors. - */ +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); -exports.Route = Route; -exports.Router = Router; + if (!match) { + return str; + } -/** - * Expose middleware - */ + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; -exports.json = bodyParser.json -exports.query = __nccwpck_require__(79768); -exports.raw = bodyParser.raw -exports.static = __nccwpck_require__(13146); -exports.text = bodyParser.text -exports.urlencoded = bodyParser.urlencoded + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } -/** - * Replace removed middleware with an appropriate error message. - */ + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] + lastIndex = index + 1; + html += escape; + } -removedMiddlewares.forEach(function (name) { - Object.defineProperty(exports, name, { - get: function () { - throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); - }, - configurable: true - }); -}); + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} /***/ }), -/***/ 92636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 98691: +/***/ ((module) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var setPrototypeOf = __nccwpck_require__(40414) - -/** - * Initialization middleware, exposing the - * request and response to each other, as well - * as defaulting the X-Powered-By header field. - * - * @param {Function} app - * @return {Function} - * @api private - */ - -exports.init = function(app){ - return function expressInit(req, res, next){ - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) - res.locals = res.locals || Object.create(null); +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } - next(); - }; + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); }; - /***/ }), -/***/ 79768: +/***/ 69972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson * MIT Licensed */ /** - * Module dependencies. + * Module exports. + * @public */ -var merge = __nccwpck_require__(44429) -var parseUrl = __nccwpck_require__(89808); -var qs = __nccwpck_require__(22760); +module.exports = etag /** - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; - - if (typeof options === 'function') { - queryparse = options; - opts = undefined; - } - - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; - } - - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); - } - - next(); - }; -}; - - -/***/ }), - -/***/ 71260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed + * Module dependencies. + * @private */ - +var crypto = __nccwpck_require__(76417) +var Stats = __nccwpck_require__(35747).Stats /** - * Module dependencies. + * Module variables. * @private */ -var accepts = __nccwpck_require__(83633); -var deprecate = __nccwpck_require__(18883)('express'); -var isIP = __nccwpck_require__(11631).isIP; -var typeis = __nccwpck_require__(71159); -var http = __nccwpck_require__(98605); -var fresh = __nccwpck_require__(83136); -var parseRange = __nccwpck_require__(26435); -var parse = __nccwpck_require__(89808); -var proxyaddr = __nccwpck_require__(80140); +var toString = Object.prototype.toString /** - * Request prototype. - * @public + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private */ -var req = Object.create(http.IncomingMessage.prototype) +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } -/** - * Module exports. - * @public - */ + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) -module.exports = req + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. + * Create a simple ETag. * - * @param {String} name + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] * @return {String} * @public */ -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') } - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') } - var lc = name.toLowerCase(); + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; - } -}; + return weak + ? 'W/' + tag + : tag +} /** - * To do: update docs. - * - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single MIME type string - * such as "application/json", an extension name - * such as "json", a comma-delimited list such as "json, html, text/plain", - * an argument list such as `"json", "html", "text/plain"`, - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given, the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html', 'json'); - * req.accepts('html, json'); - * // => "json" + * Determine if object is a Stats object. * - * @param {String|Array} type(s) - * @return {String|Array|Boolean} - * @public + * @param {object} obj + * @return {boolean} + * @api private */ -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} /** - * Check if the given `encoding`s are accepted. + * Generate a tag for a stat. * - * @param {String} ...encoding - * @return {String|Array} - * @public + * @param {object} stat + * @return {string} + * @private */ -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); + return '"' + size + '-' + mtime + '"' +} -/** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public - */ -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; +/***/ }), -req.acceptsCharset = deprecate.function(req.acceptsCharsets, - 'req.acceptsCharset: Use acceptsCharsets instead'); +/***/ 68883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Check if the given `lang`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...lang - * @return {String|Array} - * @public - */ +var original = __nccwpck_require__(80086) +var parse = __nccwpck_require__(78835).parse +var events = __nccwpck_require__(28614) +var https = __nccwpck_require__(57211) +var http = __nccwpck_require__(98605) +var util = __nccwpck_require__(31669) -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); -}; +var httpsOptions = [ + 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', + 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' +] -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} /** - * Parse Range header field, capping to the given `size`. + * Creates a new EventSource object * - * Unspecified ranges such as "0-" require knowledge of your resource length. In - * the case of a byte range this is of course the total number of bytes. If the - * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, - * and `-2` when syntactically invalid. - * - * When ranges are returned, the array has a "type" property which is the type of - * range that is required (most commonly, "bytes"). Each array element is an object - * with a "start" and "end" property for the portion of the range. - * - * The "combine" option can be set to `true` and overlapping & adjacent ranges - * will be combined into a single range. - * - * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" - * should respond with 4 users when available, not 3. - * - * @param {number} size - * @param {object} [options] - * @param {boolean} [options.combine=false] - * @return {number|array} - * @public - */ - -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; + * @param {String} url the URL to which to connect + * @param {Object} [eventSourceInitDict] extra init params. See README for details. + * @api public + **/ +function EventSource (url, eventSourceInitDict) { + var readyState = EventSource.CONNECTING + Object.defineProperty(this, 'readyState', { + get: function () { + return readyState + } + }) -/** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `bodyParser()` middleware. - * - * @param {String} name - * @param {Mixed} [defaultValue] - * @return {String} - * @public - */ + Object.defineProperty(this, 'url', { + get: function () { + return url + } + }) -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; + var self = this + self.reconnectInterval = 1000 - var args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + function onConnectionClosed (message) { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CONNECTING + _emit('error', new Event('error', {message: message})) - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; + // The url may have been changed by a temporary + // redirect. If that's the case, revert it now. + if (reconnectUrl) { + url = reconnectUrl + reconnectUrl = null + } + setTimeout(function () { + if (readyState !== EventSource.CONNECTING) { + return + } + connect() + }, self.reconnectInterval) + } - return defaultValue; -}; + var req + var lastEventId = '' + if (eventSourceInitDict && eventSourceInitDict.headers && eventSourceInitDict.headers['Last-Event-ID']) { + lastEventId = eventSourceInitDict.headers['Last-Event-ID'] + delete eventSourceInitDict.headers['Last-Event-ID'] + } -/** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param {String|Array} types... - * @return {String|false|null} - * @public - */ + var discardTrailingNewline = false + var data = '' + var eventName = '' -req.is = function is(types) { - var arr = types; + var reconnectUrl = null - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; + function connect () { + var options = parse(url) + var isSecure = options.protocol === 'https:' + options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } + if (lastEventId) options.headers['Last-Event-ID'] = lastEventId + if (eventSourceInitDict && eventSourceInitDict.headers) { + for (var i in eventSourceInitDict.headers) { + var header = eventSourceInitDict.headers[i] + if (header) { + options.headers[i] = header + } + } } - } - return typeis(this, arr); -}; + // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, + // but for now exists as a backwards-compatibility layer + options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) -/** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting trusts the socket address, the - * "X-Forwarded-Proto" header field will be trusted - * and used if present. - * - * If you're running behind a reverse proxy that - * supplies https for you this may be enabled. - * - * @return {String} - * @public - */ + // If specify http proxy, make the request to sent to the proxy server, + // and include the original url in path and Host headers + var useProxy = eventSourceInitDict && eventSourceInitDict.proxy + if (useProxy) { + var proxy = parse(eventSourceInitDict.proxy) + isSecure = proxy.protocol === 'https:' -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); + options.protocol = isSecure ? 'https:' : 'http:' + options.path = url + options.headers.Host = options.host + options.hostname = proxy.hostname + options.host = proxy.host + options.port = proxy.port + } - if (!trust(this.connection.remoteAddress, 0)) { - return proto; - } + // If https options are specified, merge them into the request options + if (eventSourceInitDict && eventSourceInitDict.https) { + for (var optName in eventSourceInitDict.https) { + if (httpsOptions.indexOf(optName) === -1) { + continue + } - // Note: X-Forwarded-Proto is normally only ever a - // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') + var option = eventSourceInitDict.https[optName] + if (option !== undefined) { + options[optName] = option + } + } + } - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() -}); + // Pass this on to the XHR + if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { + options.withCredentials = eventSourceInitDict.withCredentials + } -/** - * Short-hand for: - * - * req.protocol === 'https' - * - * @return {Boolean} - * @public - */ + req = (isSecure ? https : http).request(options, function (res) { + // Handle HTTP errors + if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + onConnectionClosed() + return + } -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); + // Handle HTTP redirects + if (res.statusCode === 301 || res.statusCode === 307) { + if (!res.headers.location) { + // Server sent redirect response without Location header. + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return + } + if (res.statusCode === 307) reconnectUrl = url + url = res.headers.location + process.nextTick(connect) + return + } -/** - * Return the remote address from the trusted proxy. - * - * The is the remote address on the socket unless - * "trust proxy" is set. - * - * @return {String} - * @public - */ + if (res.statusCode !== 200) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return self.close() + } -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); + readyState = EventSource.OPEN + res.on('close', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) -/** - * When "trust proxy" is set, trusted proxy addresses + client. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream and "proxy1" and - * "proxy2" were trusted. - * - * @return {Array} - * @public - */ + res.on('end', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + _emit('open', new Event('open')) -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); + // text/event-stream parser adapted from webkit's + // Source/WebCore/page/EventSource.cpp + var isFirst = true + var buf + res.on('data', function (chunk) { + buf = buf ? Buffer.concat([buf, chunk]) : chunk + if (isFirst && hasBom(buf)) { + buf = buf.slice(bom.length) + } - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() + isFirst = false + var pos = 0 + var length = buf.length - return addrs -}); + while (pos < length) { + if (discardTrailingNewline) { + if (buf[pos] === lineFeed) { + ++pos + } + discardTrailingNewline = false + } -/** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - * - * @return {Array} - * @public - */ + var lineLength = -1 + var fieldLength = -1 + var c -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; + for (var i = pos; lineLength < 0 && i < length; ++i) { + c = buf[i] + if (c === colon) { + if (fieldLength < 0) { + fieldLength = i - pos + } + } else if (c === carriageReturn) { + discardTrailingNewline = true + lineLength = i - pos + } else if (c === lineFeed) { + lineLength = i - pos + } + } - if (!hostname) return []; + if (lineLength < 0) { + break + } - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; + parseEventStreamLine(buf, pos, fieldLength, lineLength) - return subdomains.slice(offset); -}); + pos += lineLength + 1 + } -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @public - */ + if (pos === length) { + buf = void 0 + } else if (pos > 0) { + buf = buf.slice(pos) + } + }) + }) -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); + req.on('error', function (err) { + onConnectionClosed(err.message) + }) -/** - * Parse the "Host" header field to a hostname. - * - * When the "trust proxy" setting trusts the socket - * address, the "X-Forwarded-Host" header field will - * be trusted. - * - * @return {String} - * @public - */ + if (req.setNoDelay) req.setNoDelay(true) + req.end() + } -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); + connect() - if (!host || !trust(this.connection.remoteAddress, 0)) { - host = this.get('Host'); - } else if (host.indexOf(',') !== -1) { - // Note: X-Forwarded-Host is normally only ever a - // single value, but this is to be safe. - host = host.substring(0, host.indexOf(',')).trimRight() + function _emit () { + if (self.listeners(arguments[0]).length > 0) { + self.emit.apply(self, arguments) + } } - if (!host) return; - - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); + this._close = function () { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CLOSED + if (req.abort) req.abort() + if (req.xhr && req.xhr.abort) req.xhr.abort() + } - return index !== -1 - ? host.substring(0, index) - : host; -}); + function parseEventStreamLine (buf, pos, fieldLength, lineLength) { + if (lineLength === 0) { + if (data.length > 0) { + var type = eventName || 'message' + _emit(type, new MessageEvent(type, { + data: data.slice(0, -1), // remove trailing newline + lastEventId: lastEventId, + origin: original(url) + })) + data = '' + } + eventName = void 0 + } else if (fieldLength > 0) { + var noValue = fieldLength < 0 + var step = 0 + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() -// TODO: change req.host to return host in next major + if (noValue) { + step = lineLength + } else if (buf[pos + fieldLength + 1] !== space) { + step = fieldLength + 1 + } else { + step = fieldLength + 2 + } + pos += step -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); + var valueLength = lineLength - step + var value = buf.slice(pos, pos + valueLength).toString() -/** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @public - */ + if (field === 'data') { + data += value + '\n' + } else if (field === 'event') { + eventName = value + } else if (field === 'id') { + lastEventId = value + } else if (field === 'retry') { + var retry = parseInt(value, 10) + if (!Number.isNaN(retry)) { + self.reconnectInterval = retry + } + } + } + } +} -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode +module.exports = EventSource - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; +util.inherits(EventSource, events.EventEmitter) +EventSource.prototype.constructor = EventSource; // make stacktraces readable - // 2xx or 304 as per rfc2616 14.26 - if ((status >= 200 && status < 300) || 304 === status) { - return fresh(this.headers, { - 'etag': res.get('ETag'), - 'last-modified': res.get('Last-Modified') - }) - } +['open', 'error', 'message'].forEach(function (method) { + Object.defineProperty(EventSource.prototype, 'on' + method, { + /** + * Returns the current listener + * + * @return {Mixed} the set function or undefined + * @api private + */ + get: function get () { + var listener = this.listeners(method)[0] + return listener ? (listener._listener ? listener._listener : listener) : undefined + }, - return false; -}); + /** + * Start listening for events + * + * @param {Function} listener the listener + * @return {Mixed} the set function or undefined + * @api private + */ + set: function set (listener) { + this.removeAllListeners(method) + this.addEventListener(method, listener) + } + }) +}) /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - * - * @return {Boolean} - * @public + * Ready states */ +Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) +Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) +Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); +EventSource.prototype.CONNECTING = 0 +EventSource.prototype.OPEN = 1 +EventSource.prototype.CLOSED = 2 /** - * Check if the request was an _XMLHttpRequest_. + * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) * - * @return {Boolean} - * @public + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close + * @api public */ +EventSource.prototype.close = function () { + this._close() +} -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); +/** + * Emulates the W3C Browser based WebSocket interface using addEventListener. + * + * @param {String} type A string representing the event type to listen out for + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.addEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.addEventListener = function addEventListener (type, listener) { + if (typeof listener === 'function') { + // store a reference so we can return the original function again + listener._listener = listener + this.on(type, listener) + } +} /** - * Helper function for creating a getter on an object. + * Emulates the W3C Browser based WebSocket interface using dispatchEvent. * - * @param {Object} obj - * @param {String} name - * @param {Function} getter - * @private + * @param {Event} event An event to be dispatched + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent + * @api public */ -function defineGetter(obj, name, getter) { - Object.defineProperty(obj, name, { - configurable: true, - enumerable: true, - get: getter - }); +EventSource.prototype.dispatchEvent = function dispatchEvent (event) { + if (!event.type) { + throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') + } + // if event is instance of an CustomEvent (or has 'details' property), + // send the detail object as the payload for the event + this.emit(event.type, event.detail) +} + +/** + * Emulates the W3C Browser based WebSocket interface using removeEventListener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.removeEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { + if (typeof listener === 'function') { + listener._listener = undefined + this.removeListener(type, listener) + } +} + +/** + * W3C Event + * + * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event + * @api private + */ +function Event (type, optionalProperties) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + if (optionalProperties) { + for (var f in optionalProperties) { + if (optionalProperties.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) + } + } + } +} + +/** + * W3C MessageEvent + * + * @see http://www.w3.org/TR/webmessaging/#event-definitions + * @api private + */ +function MessageEvent (type, eventInitDict) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + for (var f in eventInitDict) { + if (eventInitDict.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) + } + } } /***/ }), -/***/ 64934: +/***/ 71204: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! * express * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + +module.exports = __nccwpck_require__(22587); + + +/***/ }), + +/***/ 313: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -45241,1139 +45260,870 @@ function defineGetter(obj, name, getter) { * @private */ -var Buffer = __nccwpck_require__(21867).Buffer -var contentDisposition = __nccwpck_require__(53921); -var deprecate = __nccwpck_require__(18883)('express'); -var encodeUrl = __nccwpck_require__(16592); -var escapeHtml = __nccwpck_require__(94070); +var finalhandler = __nccwpck_require__(30810); +var Router = __nccwpck_require__(24963); +var methods = __nccwpck_require__(58752); +var middleware = __nccwpck_require__(92636); +var query = __nccwpck_require__(79768); +var debug = __nccwpck_require__(52529)('express:application'); +var View = __nccwpck_require__(99209); var http = __nccwpck_require__(98605); -var isAbsolute = __nccwpck_require__(53561).isAbsolute; -var onFinished = __nccwpck_require__(92098); -var path = __nccwpck_require__(85622); -var statuses = __nccwpck_require__(57415) +var compileETag = __nccwpck_require__(53561).compileETag; +var compileQueryParser = __nccwpck_require__(53561).compileQueryParser; +var compileTrust = __nccwpck_require__(53561).compileTrust; +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); var merge = __nccwpck_require__(44429); -var sign = __nccwpck_require__(61579).sign; -var normalizeType = __nccwpck_require__(53561).normalizeType; -var normalizeTypes = __nccwpck_require__(53561).normalizeTypes; -var setCharset = __nccwpck_require__(53561).setCharset; -var cookie = __nccwpck_require__(93658); -var send = __nccwpck_require__(95287); -var extname = path.extname; -var mime = send.mime; -var resolve = path.resolve; -var vary = __nccwpck_require__(85931); - -/** - * Response prototype. - * @public - */ - -var res = Object.create(http.ServerResponse.prototype) +var resolve = __nccwpck_require__(85622).resolve; +var setPrototypeOf = __nccwpck_require__(40414) +var slice = Array.prototype.slice; /** - * Module exports. - * @public + * Application prototype. */ -module.exports = res +var app = exports = module.exports = {}; /** - * Module variables. + * Variable for trust proxy inheritance back-compat * @private */ -var charsetRegExp = /;\s*charset\s*=/; +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; /** - * Set status `code`. + * Initialize the server. * - * @param {Number} code - * @return {ServerResponse} - * @public + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private */ -res.status = function status(code) { - this.statusCode = code; - return this; +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); }; /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param {Object} links - * @return {ServerResponse} - * @public + * Initialize application configuration. + * @private */ -res.links = function(links){ - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); -}; +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; -/** - * Send a response. - * - * Examples: - * - * res.send(Buffer.from('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * - * @param {string|number|boolean|object|Buffer} body - * @public - */ + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); - // settings - var app = this.app; + debug('booting in %s mode', env); - // allow status / body - if (arguments.length === 2) { - // res.send(body, status) backwards compat - if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { - deprecate('res.send(body, status): Use res.status(status).send(body) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; - chunk = arguments[1]; + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; } - } - // disambiguate res.send(status) and res.send(status, num) - if (typeof chunk === 'number' && arguments.length === 1) { - // res.send(status) will set status message as text string - if (!this.get('Content-Type')) { - this.type('txt'); - } + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = statuses[chunk] - } + // setup locals + this.locals = Object.create(null); - switch (typeof chunk) { - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.type('html'); - } - break; - case 'boolean': - case 'number': - case 'object': - if (chunk === null) { - chunk = ''; - } else if (Buffer.isBuffer(chunk)) { - if (!this.get('Content-Type')) { - this.type('bin'); - } - } else { - return this.json(chunk); - } - break; - } + // top-most app is mounted at / + this.mountpath = '/'; - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); + // default locals + this.locals.settings = this.settings; - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' + if (env === 'production') { + this.enable('view cache'); + } - // populate Content-Length - var len - if (chunk !== undefined) { - if (Buffer.isBuffer(chunk)) { - // get length of Buffer - len = chunk.length - } else if (!generateETag && chunk.length < 1000) { - // just calculate length when no ETag + small chunk - len = Buffer.byteLength(chunk, encoding) - } else { - // convert chunk to Buffer and calculate - chunk = Buffer.from(chunk, encoding) - encoding = undefined; - len = chunk.length + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); } + }); +}; - this.set('Content-Length', len); - } +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); } +}; - // freshness - if (req.fresh) this.statusCode = 304; +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } +app.handle = function handle(req, res, callback) { + var router = this._router; - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; } - return this; + router.handle(req, res, done); }; /** - * Send JSON response. - * - * Examples: + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. * - * res.json(null); - * res.json({ user: 'tj' }); + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. * - * @param {string|number|boolean|object} obj * @public */ -res.json = function json(obj) { - var val = obj; +app.use = function use(fn) { + var offset = 0; + var path = '/'; - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; } } - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) + var fns = flatten(slice.call(arguments, offset)); - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') } - return this.send(body); + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; }; /** - * Send JSON response with JSONP callback support. - * - * Examples: + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. * - * @param {string|number|boolean|object} obj * @public */ -res.jsonp = function jsonp(obj) { - var val = obj; +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } - - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - var callback = this.req.query[app.get('jsonp callback name')]; - - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); - } +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); } - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); - - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); - - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; - // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" - // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; - } + // store engine + this.engines[extension] = fn; - return this.send(body); + return this; }; /** - * Send given HTTP status code. - * - * Sets the response status to `statusCode` and the body of the - * response to the standard description from node's http.STATUS_CODES - * or the statusCode number if no description. - * - * Examples: + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. * - * res.sendStatus(200); + * See the Router#param() docs for more details. * - * @param {number} statusCode + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining * @public */ -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) +app.param = function param(name, fn) { + this.lazyrouter(); - this.statusCode = statusCode; - this.type('txt'); + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } - return this.send(body); + return this; + } + + this._router.param(name, fn); + + return this; }; /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. + * Assign `setting` to `val`, or return `setting`'s value. * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); + * Mounted servers inherit their parent server's settings. * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining * @public */ -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; } - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') - } + debug('set "%s" to %o', setting, val); - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + // set value + this.settings[setting] = val; - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); - } + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + break; + } - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); + return this; }; /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. * - * Examples: + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; + * app.enabled('foo') + * // => false * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); + * app.enable('foo') + * app.enabled('foo') + * // => true * + * @param {String} setting + * @return {Boolean} * @public */ -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // create file stream - var file = send(req, path, opts); - - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); - - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); }; -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `callback(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * Check if `setting` is disabled. * - * Optionally providing an `options` object to use with `res.sendFile()`. - * This function will set the `Content-Disposition` header, overriding - * any `Content-Disposition` header passed as header options in order - * to set the attachment and filename. + * app.disabled('foo') + * // => true * - * This method uses `res.sendFile()`. + * app.enable('foo') + * app.disabled('foo') + * // => false * + * @param {String} setting + * @return {Boolean} * @public */ -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null - - // support function as second or third arg - if (typeof filename === 'function') { - done = filename; - name = null; - opts = null - } else if (typeof options === 'function') { - done = options - opts = null - } - - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; - - // merge user-provided headers - if (opts && opts.headers) { - var keys = Object.keys(opts.headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key.toLowerCase() !== 'content-disposition') { - headers[key] = opts.headers[key] - } - } - } - - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers - - // Resolve the full path for sendFile - var fullPath = resolve(path); - - // send file - return this.sendFile(fullPath, opts, done) +app.disabled = function disabled(setting) { + return !this.set(setting); }; /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); + * Enable `setting`. * - * @param {String} type - * @return {ServerResponse} for chaining + * @param {String} setting + * @return {app} for chaining * @public */ -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; - - return this.set('Content-Type', ct); +app.enable = function enable(setting) { + return this.set(setting, true); }; /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. + * Disable `setting`. * - * @param {Object} obj - * @return {ServerResponse} for chaining + * @param {String} setting + * @return {app} for chaining * @public */ -res.format = function(obj){ - var req = this.req; - var next = req.next; - - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); +app.disable = function disable(setting) { + return this.set(setting, false); +}; - var key = keys.length > 0 - ? req.accepts(keys) - : false; +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ - this.vary("Accept"); +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } - if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = err.statusCode = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); - } + this.lazyrouter(); - return this; -}; + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. * - * @param {String} filename - * @return {ServerResponse} + * @param {String} path + * @param {Function} ... + * @return {app} for chaining * @public */ -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } +app.all = function all(path) { + this.lazyrouter(); - this.set('Content-Disposition', contentDisposition(filename)); + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } return this; }; +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + /** - * Append additional header `field` with value `val`. + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. * * Example: * - * res.append('Link', ['', '']); - * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); - * res.append('Warning', '199 Miscellaneous warning'); + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) * - * @param {String} field - * @param {String|Array} val - * @return {ServerResponse} for chaining + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback * @public */ -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val]; + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - return this.set(field, value); -}; + // merge app.locals + merge(renderOptions, this.locals); -/** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - * - * @param {String|Object} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); + // merge options + merge(renderOptions, opts); - // add charset to content-type - if (field.toLowerCase() === 'content-type') { - if (Array.isArray(value)) { - throw new TypeError('Content-Type cannot be set to an Array'); - } - if (!charsetRegExp.test(value)) { - var charset = mime.charsets.lookup(value.split(';')[0]); - if (charset) value += '; charset=' + charset.toLowerCase(); - } + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); } - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); + // prime the cache + if (renderOptions.cache) { + cache[name] = view; } } - return this; + + // render + tryRender(view, renderOptions, done); }; /** - * Get value for header `field`. + * Listen for connections. * - * @param {String} field - * @return {String} + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} * @public */ -res.get = function(field){ - return this.getHeader(field); +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); }; /** - * Clear cookie `name`. + * Log error using console.error. * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public + * @param {Error} err + * @private */ -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); - - return this.cookie(name, '', opts); -}; +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} /** - * Set cookie `name` to `value`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // same as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - * - * @param {String} name - * @param {String|Object} value - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public + * Try rendering a view. + * @private */ -res.cookie = function (name, value, options) { - var opts = merge({}, options); - var secret = this.req.secret; - var signed = opts.signed; - - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); } +} - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); - if (signed) { - val = 's:' + sign(val, secret); - } +/***/ }), - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; - } +/***/ 22587: +/***/ ((module, exports, __nccwpck_require__) => { - if (opts.path == null) { - opts.path = '/'; - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); - return this; -}; /** - * Set the location header to `url`. - * - * The given `url` can also be "back", which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); - * - * @param {String} url - * @return {ServerResponse} for chaining - * @public + * Module dependencies. */ -res.location = function location(url) { - var loc = url; +var bodyParser = __nccwpck_require__(97076) +var EventEmitter = __nccwpck_require__(28614).EventEmitter; +var mixin = __nccwpck_require__(11149); +var proto = __nccwpck_require__(313); +var Route = __nccwpck_require__(23699); +var Router = __nccwpck_require__(24963); +var req = __nccwpck_require__(71260); +var res = __nccwpck_require__(64934); - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; - } +/** + * Expose `createApplication()`. + */ - // set location - return this.set('Location', encodeUrl(loc)); -}; +exports = module.exports = createApplication; /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('../login'); // /blog/post/1 -> /blog/login + * Create an express application. * - * @public + * @return {Function} + * @api public */ -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; - - // allow status / url - if (arguments.length === 2) { - if (typeof arguments[0] === 'number') { - status = arguments[0]; - address = arguments[1]; - } else { - deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); - status = arguments[1]; - } - } +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; - // Set location header - address = this.location(address).get('Location'); + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) - html: function(){ - var u = escapeHtml(address); - body = '

' + statuses[status] + '. Redirecting to ' + u + '

' - }, + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) - default: function(){ - body = ''; - } - }); + app.init(); + return app; +} - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); +/** + * Expose the prototypes. + */ - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); - } -}; +exports.application = proto; +exports.request = req; +exports.response = res; /** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. - * - * @param {Array|String} field - * @return {ServerResponse} for chaining - * @public + * Expose constructors. */ -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; - } +exports.Route = Route; +exports.Router = Router; - vary(this, field); +/** + * Expose middleware + */ - return this; -}; +exports.json = bodyParser.json +exports.query = __nccwpck_require__(79768); +exports.raw = bodyParser.raw +exports.static = __nccwpck_require__(13146); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - * - * @public + * Replace removed middleware with an appropriate error message. */ -res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self = this; +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); - // merge res.locals - opts._locals = self.locals; - // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; +/***/ }), - // render - app.render(view, opts, done); -}; +/***/ 92636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // request aborted - function onaborted() { - if (done) return; - done = true; - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); - } - // directory - function ondirectory() { - if (done) return; - done = true; +/** + * Module dependencies. + * @private + */ - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } +var setPrototypeOf = __nccwpck_require__(40414) - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); - } +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ - // ended - function onend() { - if (done) return; - done = true; - callback(); - } +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; - // file - function onfile() { - streaming = false; - } + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; + res.locals = res.locals || Object.create(null); - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } + next(); + }; +}; - if (done) return; - done = true; - callback(); - }); - } - // streaming - function onstream() { - streaming = true; - } - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); +/***/ }), - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); +/***/ 79768: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); - } - // pipe - file.pipe(res); -} /** - * Stringify JSON, like JSON.stringify, but v8 optimized, with the - * ability to escape characters that can trigger HTML sniffing. - * - * @param {*} value - * @param {function} replaces - * @param {number} spaces - * @param {boolean} escape - * @returns {string} - * @private + * Module dependencies. */ -function stringify (value, replacer, spaces, escape) { - // v8 checks arguments.length for optimizing simple call - // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces - ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); +var merge = __nccwpck_require__(44429) +var parseUrl = __nccwpck_require__(89808); +var qs = __nccwpck_require__(22760); - if (escape) { - json = json.replace(/[<>&]/g, function (c) { - switch (c.charCodeAt(0)) { - case 0x3c: - return '\\u003c' - case 0x3e: - return '\\u003e' - case 0x26: - return '\\u0026' - /* istanbul ignore next: unreachable default */ - default: - return c - } - }) +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; } - return json -} + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; /***/ }), -/***/ 24963: +/***/ 71260: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -46392,1385 +46142,1671 @@ function stringify (value, replacer, spaces, escape) { * @private */ -var Route = __nccwpck_require__(23699); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); -var mixin = __nccwpck_require__(44429); -var debug = __nccwpck_require__(52529)('express:router'); +var accepts = __nccwpck_require__(83633); var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var parseUrl = __nccwpck_require__(89808); -var setPrototypeOf = __nccwpck_require__(40414) +var isIP = __nccwpck_require__(11631).isIP; +var typeis = __nccwpck_require__(71159); +var http = __nccwpck_require__(98605); +var fresh = __nccwpck_require__(83136); +var parseRange = __nccwpck_require__(26435); +var parse = __nccwpck_require__(89808); +var proxyaddr = __nccwpck_require__(80140); /** - * Module variables. - * @private + * Request prototype. + * @public */ -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +var req = Object.create(http.IncomingMessage.prototype) /** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function + * Module exports. * @public */ -var proto = module.exports = function(options) { - var opts = options || {}; - - function router(req, res, next) { - router.handle(req, res, next); - } - - // mixin Router class functions - setPrototypeOf(router, proto) - - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; - - return router; -}; +module.exports = req /** - * Map the given param placeholder `name`(s) to the given callback. + * Return request header. * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. + * Examples: * - * Just like in middleware, you must either respond to the request or call next - * to avoid stalling the request. + * req.get('Content-Type'); + * // => "text/plain" * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * return next(err); - * } else if (!user) { - * return next(new Error('failed to load user')); - * } - * req.user = user; - * next(); - * }); - * }); + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. * * @param {String} name - * @param {Function} fn - * @return {app} for chaining + * @return {String} * @public */ -proto.param = function param(name, fn) { - // param logic - if (typeof name === 'function') { - deprecate('router.param(fn): Refactor to use path params'); - this._params.push(name); - return; +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); } - // apply param functions - var params = this._params; - var len = params.length; - var ret; - - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); } - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } - } + var lc = name.toLowerCase(); - // ensure we end up with a - // middleware function - if ('function' !== typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; } +}; - (this.params[name] = this.params[name] || []).push(fn); - return this; +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); }; /** - * Dispatch a req, res into the router. - * @private + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public */ -proto.handle = function handle(req, res, out) { - var self = this; +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; - debug('dispatching %s %s', req.method, req.url); +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; - // middleware and routes - var stack = self.stack; +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ - // setup next layer - req.next = next; +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; - // for options requests, respond with a default if nothing else responds - if (req.method === 'OPTIONS') { - done = wrap(done, function(old, err) { - if (err || options.length === 0) return old(err); - sendOptionsResponse(res, options, old); - }); - } +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ - next(); +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; - function next(err) { - var layerError = err === 'route' - ? null - : err; +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return - } + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } + return defaultValue; +}; - // get pathname of request - var path = getPathname(req); +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ - if (path == null) { - return done(layerError); - } +req.is = function is(types) { + var arr = types; - // find next matching layer - var layer; - var match; - var route; + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; + return typeis(this, arr); +}; - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ - if (match !== true) { - continue; - } +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); - if (!route) { - // process non-route handlers normally - continue; - } + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } - - var method = req.method; - var has_method = route._handles_method(method); + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ - // no match - if (match !== true) { - return done(layerError); - } +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); - // store route for dispatch on change - if (route) { - req.route = route; - } +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ - if (route) { - return layer.handle_request(req, res, next); - } +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); - trim_prefix(layer, layerError, layerPath, path); - }); - } + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() - function trim_prefix(layer, layerError, layerPath, path) { - if (layerPath.length !== 0) { - // Validate path breaks on a path separator - var c = path[layerPath.length] - if (c && c !== '/' && c !== '.') return next(layerError) + return addrs +}); - // Trim off the part of the url that matches the route - // middleware (.use stuff) needs to have the path stripped - debug('trim prefix (%s) from url %s', layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.substr(protohost.length + removed.length); +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } + if (!hostname) return []; - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; + return subdomains.slice(offset); +}); /** - * Process any parameters for the layer. - * @private + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public */ -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); - // captured parameters from the layer, keys and values - var keys = layer.keys; +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ - // fast track - if (!keys || keys.length === 0) { - return done(); +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() } - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; + if (!host) return; - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); - if (i >= keys.length ) { - return done(); - } + return index !== -1 + ? host.substring(0, index) + : host; +}); - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; +// TODO: change req.host to return host in next major - if (paramVal === undefined || !paramCallbacks) { - return param(); - } +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); - // param previously called with same value or error occurred - if (paramCalled && (paramCalled.match === paramVal - || (paramCalled.error && paramCalled.error !== 'route'))) { - // restore value - req.params[name] = paramCalled.value; +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ - // next param - return param(paramCalled.error); - } +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; - paramCallback(); + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) } - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - - // store updated value - paramCalled.value = req.params[key.name]; + return false; +}); - if (err) { - // store error - paramCalled.error = err; - param(err); - return; - } +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ - if (!fn) return param(); +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); - } - } +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ - param(); -}; +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); /** - * Use the given middleware function, with optional path, defaulting to "/". - * - * Use (like `.all`) will run for any http METHOD, but it will not add - * handlers for those methods so OPTIONS requests will not consider `.use` - * functions even if they could respond. - * - * The other difference is that _route_ path is stripped and not visible - * to the handler function. The main effect of this feature is that mounted - * handlers can operate without any code changes regardless of the "prefix" - * pathname. + * Helper function for creating a getter on an object. * - * @public + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} -proto.use = function use(fn) { - var offset = 0; - var path = '/'; - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; +/***/ }), - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } +/***/ 64934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - var callbacks = flatten(slice.call(arguments, offset)); - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') - } - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; +/** + * Module dependencies. + * @private + */ - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) - } +var Buffer = __nccwpck_require__(21867).Buffer +var contentDisposition = __nccwpck_require__(53921); +var deprecate = __nccwpck_require__(18883)('express'); +var encodeUrl = __nccwpck_require__(16592); +var escapeHtml = __nccwpck_require__(94070); +var http = __nccwpck_require__(98605); +var isAbsolute = __nccwpck_require__(53561).isAbsolute; +var onFinished = __nccwpck_require__(92098); +var path = __nccwpck_require__(85622); +var statuses = __nccwpck_require__(57415) +var merge = __nccwpck_require__(44429); +var sign = __nccwpck_require__(61579).sign; +var normalizeType = __nccwpck_require__(53561).normalizeType; +var normalizeTypes = __nccwpck_require__(53561).normalizeTypes; +var setCharset = __nccwpck_require__(53561).setCharset; +var cookie = __nccwpck_require__(66515); +var send = __nccwpck_require__(95287); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = __nccwpck_require__(85931); - // add the middleware - debug('use %o %s', path, fn.name || '') +/** + * Response prototype. + * @public + */ - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); +var res = Object.create(http.ServerResponse.prototype) - layer.route = undefined; +/** + * Module exports. + * @public + */ - this.stack.push(layer); - } +module.exports = res + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ +res.status = function status(code) { + this.statusCode = code; return this; }; /** - * Create a new Route for the given path. + * Set Link header field with the given `links`. * - * Each route contains a separate middleware stack and VERB handlers. + * Examples: * - * See the Route api documentation for details on adding handlers - * and middleware to routes. + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); * - * @param {String} path - * @return {Route} + * @param {Object} links + * @return {ServerResponse} * @public */ -proto.route = function route(path) { - var route = new Route(path); - - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, route.dispatch.bind(route)); +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; - layer.route = route; +/** + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ - this.stack.push(layer); - return route; -}; +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; -// create Router#VERB functions -methods.concat('all').forEach(function(method){ - proto[method] = function(path){ - var route = this.route(path) - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); + // settings + var app = this.app; -// append methods to a list of methods -function appendMethods(list, addition) { - for (var i = 0; i < addition.length; i++) { - var method = addition[i]; - if (list.indexOf(method) === -1) { - list.push(method); + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; } } -} -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] } -} -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; } - var searchIndex = url.indexOf('?') - var pathLength = searchIndex !== -1 - ? searchIndex - : url.length - var fqdnIndex = url.substr(0, pathLength).indexOf('://') - - return fqdnIndex !== -1 - ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) - : undefined -} - -// get type for error message -function gettype(obj) { - var type = typeof obj; + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); - if (type !== 'object') { - return type; + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } } - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); -} + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' -/** - * Match path to a layer. - * - * @param {Layer} layer - * @param {string} path - * @private - */ + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } -function matchLayer(layer, path) { - try { - return layer.match(path); - } catch (err) { - return err; + this.set('Content-Length', len); } -} -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } } - // make copy of parent for base - var obj = mixin({}, parent); + // freshness + if (req.fresh) this.statusCode = 304; - // simple non-numeric merging - if (!(0 in params) || !(0 in parent)) { - return mixin(obj, params); + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; } - var i = 0; - var o = 0; - - // determine numeric gaps - while (i in params) { - i++; + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); } - while (o in parent) { - o++; - } + return this; +}; - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ - // create holes for the merge when necessary - if (i < o) { - delete params[i]; +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; } } - return mixin(obj, params); -} - -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); } - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; - } - - return fn.apply(this, arguments); - }; -} + return this.send(body); +}; -// send an OPTIONS response -function sendOptionsResponse(res, options, next) { - try { - var body = options.join(','); - res.set('Allow', body); - res.send(body); - } catch (err) { - next(err); - } -} +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); +res.jsonp = function jsonp(obj) { + var val = obj; - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; } + } - fn.apply(this, args); - }; -} + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } -/***/ }), + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } -/***/ 25624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + return this.send(body); +}; /** - * Module dependencies. - * @private + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public */ -var pathRegexp = __nccwpck_require__(37819); -var debug = __nccwpck_require__(52529)('express:router:layer'); +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) -/** - * Module variables. - * @private - */ + this.statusCode = statusCode; + this.type('txt'); -var hasOwnProperty = Object.prototype.hasOwnProperty; + return this.send(body); +}; /** - * Module exports. + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * * @public */ -module.exports = Layer; +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); } - debug('new %o', path) - var opts = options || {}; - - this.handle = fn; - this.name = fn.name || ''; - this.params = undefined; - this.path = undefined; - this.regexp = pathRegexp(path, this.keys = [], opts); + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') + } - // set fast path flags - this.regexp.fast_star = path === '*' - this.regexp.fast_slash = path === '/' && opts.end === false -} + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } -/** - * Handle the error for the layer. - * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); - if (fn.length !== 4) { - // not a standard error handler - return next(error); - } + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); - try { - fn(error, req, res, next); - } catch (err) { - next(err); - } + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); }; /** - * Handle the request for the layer. + * Transfer the file at the given `path`. * - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public */ -Layer.prototype.handle_request = function handle(req, res, next) { - var fn = this.handle; +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; - if (fn.length > 3) { - // not a standard request handler - return next(); + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - try { - fn(req, res, next); - } catch (err) { - next(err); - } + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); }; +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + /** - * Check if this route matches `path`, if so - * populate `.params`. + * Transfer the file at the given `path` as an attachment. * - * @param {String} path - * @return {Boolean} - * @api private + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public */ -Layer.prototype.match = function match(path) { - var match - - if (path != null) { - // fast path non-ending match for / (any path matches) - if (this.regexp.fast_slash) { - this.params = {} - this.path = '' - return true - } +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true - } - - // match the path - match = this.regexp.exec(path) + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null } - if (!match) { - this.params = undefined; - this.path = undefined; - return false; + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } } - // store values - this.params = {}; - this.path = match[0] + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers - var keys = this.keys; - var params = this.params; + // Resolve the full path for sendFile + var fullPath = resolve(path); - for (var i = 1; i < match.length; i++) { - var key = keys[i - 1]; - var prop = key.name; - var val = decode_param(match[i]) + // send file + return this.sendFile(fullPath, opts, done) +}; - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; - } - } +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ - return true; +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); }; /** - * Decode param value. + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. * - * @param {string} val - * @return {string} - * @private + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public */ -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; - } +res.format = function(obj){ + var req = this.req; + var next = req.next; - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; - } + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); - throw err; - } -} + var key = keys.length > 0 + ? req.accepts(keys) + : false; + this.vary("Accept"); -/***/ }), + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = err.statusCode = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); + } -/***/ 23699: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this; +}; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public */ +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + return this; +}; /** - * Module dependencies. - * @private + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public */ -var debug = __nccwpck_require__(52529)('express:router:route'); -var flatten = __nccwpck_require__(62003); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } + + return this.set(field, value); +}; /** - * Module variables. - * @private + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public */ -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; /** - * Module exports. + * Get value for header `field`. + * + * @param {String} field + * @return {String} * @public */ -module.exports = Route; +res.get = function(field){ + return this.getHeader(field); +}; /** - * Initialize `Route` with the given `path`, + * Clear cookie `name`. * - * @param {String} path + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining * @public */ -function Route(path) { - this.path = path; - this.stack = []; - - debug('new %o', path) +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); - // route handlers for various http methods - this.methods = {}; -} + return this.cookie(name, '', opts); +}; /** - * Determine if the route handles a given method. - * @private + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public */ -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; + + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); } - var name = method.toLowerCase(); + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); - if (name === 'head' && !this.methods['head']) { - name = 'get'; + if (signed) { + val = 's:' + sign(val, secret); } - return Boolean(this.methods[name]); + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } + + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; }; /** - * @return {Array} supported HTTP methods - * @private + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public */ -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); - - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); - } +res.location = function location(url) { + var loc = url; - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; } - return methods; + // set location + return this.set('Location', encodeUrl(loc)); }; /** - * dispatch req, res into this route - * @private + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public */ -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; + } } - req.route = this; - - next(); + // Set location header + address = this.location(address).get('Location'); - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, - // signal to exit router - if (err && err === 'router') { - return done(err) - } + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses[status] + '. Redirecting to ' + u + '

' + }, - var layer = stack[idx++]; - if (!layer) { - return done(err); + default: function(){ + body = ''; } + }); - if (layer.method && layer.method !== method) { - return next(err); - } + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); } }; /** - * Add a handler for all HTTP verbs to this route. - * - * Behaves just like middleware and can respond or call `next` - * to continue processing. - * - * You can use multiple `.all` call to add multiple handlers. - * - * function check_something(req, res, next){ - * next(); - * }; - * - * function validate_user(req, res, next){ - * next(); - * }; - * - * route - * .all(validate_user) - * .all(check_something) - * .get(function(req, res, next){ - * res.send('hello world'); - * }); + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. * - * @param {function} handler - * @return {Route} for chaining - * @api public + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public */ -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; - - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.all() requires a callback function but got a ' + type - throw new TypeError(msg); - } - - var layer = Layer('/', {}, handle); - layer.method = undefined; - - this.methods._all = true; - this.stack.push(layer); - } + vary(this, field); return this; }; -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); - - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; - - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.' + method + '() requires a callback function but got a ' + type - throw new Error(msg); - } - - debug('%s %o', method, this.path) - - var layer = Layer('/', {}, handle); - layer.method = method; - - this.methods[method] = true; - this.stack.push(layer); - } - - return this; - }; -}); - - -/***/ }), - -/***/ 53561: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @api private - */ - -var Buffer = __nccwpck_require__(21867).Buffer -var contentDisposition = __nccwpck_require__(53921); -var contentType = __nccwpck_require__(99915); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var mime = __nccwpck_require__(95287).mime; -var etag = __nccwpck_require__(69972); -var proxyaddr = __nccwpck_require__(80140); -var qs = __nccwpck_require__(22760); -var querystring = __nccwpck_require__(71191); - -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ - -exports.etag = createETagGenerator({ weak: false }) - -/** - * Return weak ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ - -exports.wetag = createETagGenerator({ weak: true }) - -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -exports.isAbsolute = function(path){ - if ('/' === path[0]) return true; - if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path - if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path -}; - /** - * Flatten the given `arr`. + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. * - * @param {Array} arr - * @return {Array} - * @api private - */ - -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); - -/** - * Normalize the given `type`, for example "html" becomes "text/html". + * Options: * - * @param {String} type - * @return {Object} - * @api private - */ - -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; -}; - -/** - * Normalize `types`, for example "html" becomes "text/html". + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered * - * @param {Array} types - * @return {Array} - * @api private + * @public */ -exports.normalizeTypes = function(types){ - var ret = []; +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - return ret; -}; + // merge res.locals + opts._locals = self.locals; -/** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added - * - * @param {String} filename - * @return {String} - * @api private - */ + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); + // render + app.render(view, opts, done); +}; -/** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting - * - * @param {String} str - * @return {Object} - * @api private - */ +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + // request aborted + function onaborted() { + if (done) return; + done = true; - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' === pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; - } + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); } - return ret; -} - -/** - * Compile "etag" value to function. - * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private - */ - -exports.compileETag = function(val) { - var fn; + // directory + function ondirectory() { + if (done) return; + done = true; - if (typeof val === 'function') { - return val; + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); } - switch (val) { - case true: - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - case 'weak': - fn = exports.wetag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); } - return fn; -} - -/** - * Compile "query parser" value to function. - * - * @param {String|Function} val - * @return {Function} - * @api private - */ - -exports.compileQueryParser = function compileQueryParser(val) { - var fn; - - if (typeof val === 'function') { - return val; + // ended + function onend() { + if (done) return; + done = true; + callback(); } - switch (val) { - case true: - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - case 'simple': - fn = querystring.parse; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); + // file + function onfile() { + streaming = false; } - return fn; -} - -/** - * Compile "proxy trust" value to function. - * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private - */ - -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; - if (val === true) { - // Support plain true/false - return function(){ return true }; - } + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; + if (done) return; + done = true; + callback(); + }); } - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); + // streaming + function onstream() { + streaming = true; } - return proxyaddr.compile(val || []); -} + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); -/** - * Set the charset in a given Content-Type string. - * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private - */ + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); } - // parse type - var parsed = contentType.parse(type); - - // set charset - parsed.parameters.charset = charset; - - // format type - return contentType.format(parsed); -}; - -/** - * Create an ETag generator function, generating ETags with - * the given options. - * - * @param {object} options - * @return {function} - * @private - */ - -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body - - return etag(buf, options) - } + // pipe + file.pipe(res); } /** - * Parse an extended query string with qs. + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. * - * @return {Object} + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} * @private */ -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); -} +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); -/** - * Return new empty object. - * - * @return {Object} - * @api private - */ + if (escape) { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) + } -function newObject() { - return {}; + return json } /***/ }), -/***/ 99209: +/***/ 24963: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -47789,48968 +47825,48338 @@ function newObject() { * @private */ -var debug = __nccwpck_require__(52529)('express:view'); -var path = __nccwpck_require__(85622); -var fs = __nccwpck_require__(35747); +var Route = __nccwpck_require__(23699); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); +var mixin = __nccwpck_require__(44429); +var debug = __nccwpck_require__(52529)('express:router'); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var parseUrl = __nccwpck_require__(89808); +var setPrototypeOf = __nccwpck_require__(40414) /** * Module variables. * @private */ -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; - -/** - * Module exports. - * @public - */ - -module.exports = View; +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; /** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup + * Initialize a new `Router` with the given `options`. * - * @param {string} name - * @param {object} options + * @param {Object} [options] + * @return {Router} which is an callable function * @public */ -function View(name, options) { +var proto = module.exports = function(options) { var opts = options || {}; - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; - - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); - } - - var fileName = name; - - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; - - fileName += this.ext; + function router(req, res, next) { + router.handle(req, res, next); } - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) + // mixin Router class functions + setPrototypeOf(router, proto) - // default engine export - var fn = require(mod).__express + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') - } - - opts.engines[this.ext] = fn - } - - // store loaded engine - this.engine = opts.engines[this.ext]; - - // lookup path - this.path = this.lookup(fileName); -} + return router; +}; /** - * Lookup view by the given `name` + * Map the given param placeholder `name`(s) to the given callback. * - * @param {string} name - * @private + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public */ -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } - debug('lookup "%s"', name); + // apply param functions + var params = this._params; + var len = params.length; + var ret; - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } - // resolve the file - path = this.resolve(dir, file); + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); } - return path; + (this.params[name] = this.params[name] || []).push(fn); + return this; }; /** - * Render with the given options. - * - * @param {object} options - * @param {function} callback + * Dispatch a req, res into the router. * @private */ -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; +proto.handle = function handle(req, res, out) { + var self = this; -/** - * Resolve the file within the given directory. - * - * @param {string} dir - * @param {string} file - * @private - */ + debug('dispatching %s %s', req.method, req.url); -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; - // . - var path = join(dir, file); - var stat = tryStat(path); + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; - if (stat && stat.isFile()) { - return path; - } + // middleware and routes + var stack = self.stack; - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); - if (stat && stat.isFile()) { - return path; + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); } -}; -/** - * Return a stat, maybe. - * - * @param {string} path - * @return {fs.Stats} - * @private - */ + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; -function tryStat(path) { - debug('stat "%s"', path); + next(); - try { - return fs.statSync(path); - } catch (e) { - return undefined; - } -} + function next(err) { + var layerError = err === 'route' + ? null + : err; + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } -/***/ }), + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; + } -/***/ 36654: -/***/ ((module, exports, __nccwpck_require__) => { + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } -exports = module.exports = __nccwpck_require__(86991); -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(); + // get pathname of request + var path = getPathname(req); -/** - * Colors. - */ + if (path == null) { + return done(layerError); + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + // find next matching layer + var layer; + var match; + var route; -/** - * 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 - */ + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; -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 (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } - // 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+)/)); -} + if (match !== true) { + continue; + } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (!route) { + // process non-route handlers normally + continue; + } -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + var method = req.method; + var has_method = route._handles_method(method); -/** - * Colorize log arguments if enabled. - * - * @api public - */ + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } -function formatArgs(args) { - var useColors = this.useColors; + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } + } - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + // no match + if (match !== true) { + return done(layerError); + } - if (!useColors) return; + // store route for dispatch on change + if (route) { + req.route = route; + } - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; - // 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; - } - }); + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } - args.splice(lastC, 0, c); -} + if (route) { + return layer.handle_request(req, res, next); + } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + trim_prefix(layer, layerError, layerPath, path); + }); + } -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 trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); } else { - exports.storage.debug = namespaces; + layer.handle_request(req, res, next); } - } catch(e) {} -} + } +}; /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Process any parameters for the layer. + * @private */ -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; - // 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; + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); } - return r; -} + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } -exports.enable(load()); + if (i >= keys.length ) { + return done(); + } -/** - * 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 - */ + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; -/***/ }), + // next param + return param(paramCalled.error); + } -/***/ 86991: -/***/ ((module, exports, __nccwpck_require__) => { + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + paramCallback(); + } -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(27025); + // store updated value + paramCalled.value = req.params[key.name]; -/** - * The currently active debug mode names, and names to skip. - */ + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } -exports.names = []; -exports.skips = []; + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; /** - * Map of special "%n" handling functions, for the debug "format" argument. + * Use the given middleware function, with optional path, defaulting to "/". * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public */ -exports.formatters = {}; +proto.use = function use(fn) { + var offset = 0; + var path = '/'; -/** - * Previous log timestamp. - */ + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; -var prevTime; + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } -function selectColor(namespace) { - var hash = 0, i; + var callbacks = flatten(slice.call(arguments, offset)); - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; /** - * Create a debugger with the given `namespace`. + * Create a new Route for the given path. * - * @param {String} namespace - * @return {Function} - * @api public + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public */ -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; +proto.route = function route(path) { + var route = new Route(path); - var self = debug; + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + layer.route = route; - // 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]; - } + this.stack.push(layer); + return route; +}; - args[0] = exports.coerce(args[0]); +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); } + } +} - // 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); +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +// get type for error message +function gettype(obj) { + var type = typeof obj; - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); + if (type !== 'object') { + return type; } - return debug; + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); } /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. + * Match path to a layer. * - * @param {String} namespaces - * @api public + * @param {Layer} layer + * @param {string} path + * @private */ -function enable(namespaces) { - exports.save(namespaces); +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} - exports.names = []; - exports.skips = []; +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + // make copy of parent for base + var obj = mixin({}, parent); - 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 + '$')); - } + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); } -} - -/** - * Disable debug output. - * - * @api public - */ -function disable() { - exports.enable(''); -} + var i = 0; + var o = 0; -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + // determine numeric gaps + while (i in params) { + i++; + } -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } + while (o in parent) { + o++; } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; } } - return false; + + return mixin(obj, params); } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } -/***/ }), + return fn.apply(this, arguments); + }; +} -/***/ 52529: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(36654); -} else { - module.exports = __nccwpck_require__(25696); + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; } /***/ }), -/***/ 25696: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 25624: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Module dependencies. +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); - -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ -exports = module.exports = __nccwpck_require__(86991); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; /** - * Colors. + * Module dependencies. + * @private */ -exports.colors = [6, 2, 3, 4, 5, 1]; +var pathRegexp = __nccwpck_require__(37819); +var debug = __nccwpck_require__(52529)('express:router:layer'); /** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * Module variables. + * @private */ -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); +var hasOwnProperty = Object.prototype.hasOwnProperty; /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log + * Module exports. + * @public */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +module.exports = Layer; -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + debug('new %o', path) + var opts = options || {}; -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false } /** - * Map %o to `util.inspect()`, all on a single line. + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private */ -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } }; /** - * Adds ANSI color escape codes if enabled. + * Handle the request for the layer. * - * @api public + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private */ -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + if (fn.length > 3) { + // not a standard request handler + return next(); + } - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; + try { + fn(req, res, next); + } catch (err) { + next(err); } -} +}; /** - * Invokes `util.format()` with the specified arguments and writes to `stream`. + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +Layer.prototype.match = function match(path) { + var match -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } -function load() { - return process.env.DEBUG; -} + // match the path + match = this.regexp.exec(path) + } -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); + // store values + this.params = {}; + this.path = match[0] - // Note stream._type is used for test-module-load-list.js + var keys = this.keys; + var params = this.params; - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } - case 'FILE': - var fs = __nccwpck_require__(35747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + return true; +}; - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(11631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); + throw err; } +} - // For supporting legacy API we put the FD here. - stream.fd = fd; - stream._isStdio = true; +/***/ }), - return stream; -} +/***/ 23699: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -function init (debug) { - debug.inspectOpts = {}; - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Module dependencies. + * @private */ -exports.enable(load()); - - -/***/ }), - -/***/ 27025: -/***/ ((module) => { +var debug = __nccwpck_require__(52529)('express:router:route'); +var flatten = __nccwpck_require__(62003); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); /** - * Helpers. + * Module variables. + * @private */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * Module exports. + * @public */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +module.exports = Route; /** - * Parse the given `str` and return milliseconds. + * Initialize `Route` with the given `path`, * - * @param {String} str - * @return {Number} - * @api private + * @param {String} path + * @public */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; } /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Determine if the route handles a given method. + * @private */ -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; } - if (ms >= s) { - return Math.round(ms / s) + 's'; + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; } - return ms + 'ms'; -} + + return Boolean(this.methods[name]); +}; /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * @return {Array} supported HTTP methods + * @private */ -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; +}; /** - * Pluralization helper. + * dispatch req, res into this route + * @private */ -function plural(ms, n, name) { - if (ms < n) { - return; +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + req.route = this; -/***/ }), + next(); -/***/ 24826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } -"use strict"; + // signal to exit router + if (err && err === 'router') { + return done(err) + } + var layer = stack[idx++]; + if (!layer) { + return done(err); + } -const validator = __nccwpck_require__(74174) -const parse = __nccwpck_require__(96214) -const redactor = __nccwpck_require__(17333) -const restorer = __nccwpck_require__(98806) -const { groupRedact, nestedRedact } = __nccwpck_require__(54865) -const state = __nccwpck_require__(41012) -const rx = __nccwpck_require__(9158) -const validate = validator() -const noop = (o) => o -noop.restore = noop + if (layer.method && layer.method !== method) { + return next(err); + } -const DEFAULT_CENSOR = '[REDACTED]' -fastRedact.rx = rx -fastRedact.validator = validator + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; -module.exports = fastRedact +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ -function fastRedact (opts = {}) { - const paths = Array.from(new Set(opts.paths || [])) - const serialize = 'serialize' in opts ? ( - opts.serialize === false ? opts.serialize - : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) - ) : JSON.stringify - const remove = opts.remove - if (remove === true && serialize !== JSON.stringify) { - throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); } - const censor = remove === true - ? undefined - : 'censor' in opts ? opts.censor : DEFAULT_CENSOR - const isCensorFct = typeof censor === 'function' - const censorFctTakesPath = isCensorFct && censor.length > 1 + return this; +}; - if (paths.length === 0) return serialize || noop +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); - validate({ paths, serialize, censor }) + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; - const { wildcards, wcLen, secret } = parse({ paths, censor }) + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } - const compileRestore = restorer({ secret, wcLen }) - const strict = 'strict' in opts ? opts.strict : true + debug('%s %o', method, this.path) - return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - })) -} + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); /***/ }), -/***/ 54865: -/***/ ((module) => { +/***/ 53561: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -module.exports = { - groupRedact, - groupRestore, - nestedRedact, - nestedRestore -} -function groupRestore ({ keys, values, target }) { - if (target == null) return - const length = keys.length - for (var i = 0; i < length; i++) { - const k = keys[i] - target[k] = values[i] - } -} +/** + * Module dependencies. + * @api private + */ -function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return { keys: null, values: null, target: null, flat: true } - const keys = Object.keys(target) - const keysLength = keys.length - const pathLength = path.length - const pathWithKey = censorFctTakesPath ? [...path] : undefined - const values = new Array(keysLength) +var Buffer = __nccwpck_require__(21867).Buffer +var contentDisposition = __nccwpck_require__(53921); +var contentType = __nccwpck_require__(99915); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var mime = __nccwpck_require__(95287).mime; +var etag = __nccwpck_require__(69972); +var proxyaddr = __nccwpck_require__(80140); +var qs = __nccwpck_require__(22760); +var querystring = __nccwpck_require__(71191); - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - values[i] = target[key] +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ - if (censorFctTakesPath) { - pathWithKey[pathLength] = key - target[key] = censor(target[key], pathWithKey) - } else if (isCensorFct) { - target[key] = censor(target[key]) - } else { - target[key] = censor - } - } - return { keys, values, target, flat: true } -} +exports.etag = createETagGenerator({ weak: false }) -function nestedRestore (arr) { - const length = arr.length - for (var i = 0; i < length; i++) { - const { key, target, value } = arr[i] - target[key] = value - } -} +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ -function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return - const keys = Object.keys(target) - const keysLength = keys.length - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - const { value, parent, exists } = - specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) +exports.wetag = createETagGenerator({ weak: true }) - if (exists === true && parent !== null) { - store.push({ key: ns[ns.length - 1], target: parent, value }) - } - } - return store -} +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ -function has (obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop) -} +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; -function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { - const afterPathLen = afterPath.length - const lastPathIndex = afterPathLen - 1 - const originalKey = k - var i = -1 - var n - var nv - var ov - var oov = null - var exists = true - ov = n = o[k] - if (typeof n !== 'object') return { value: null, parent: null, exists } - while (n != null && ++i < afterPathLen) { - k = afterPath[i] - oov = ov - if (!(k in n)) { - exists = false - break - } - ov = n[k] - nv = (i !== lastPathIndex) - ? ov - : (isCensorFct - ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) - : censor) - n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv - n = n[k] - if (typeof n !== 'object') break - } - return { value: ov, parent: oov, exists } -} +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ -function get (o, p) { - var i = -1 - var l = p.length - var n = o - while (n != null && ++i < l) { - n = n[p[i]] - } - return n -} +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ -/***/ }), +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; -/***/ 96214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ -"use strict"; +exports.normalizeTypes = function(types){ + var ret = []; + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } -const rx = __nccwpck_require__(9158) + return ret; +}; -module.exports = parse +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ -function parse ({ paths }) { - const wildcards = [] - var wcLen = 0 - const secret = paths.reduce(function (o, strPath, ix) { - var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) - const leadingBracket = strPath[0] === '[' - path = path.map((p) => { - if (p[0] === '[') return p.substr(1, p.length - 2) - else return p - }) - const star = path.indexOf('*') - if (star > -1) { - const before = path.slice(0, star) - const beforeStr = before.join('.') - const after = path.slice(star + 1, path.length) - if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') - const nested = after.length > 0 - wcLen++ - wildcards.push({ - before, - beforeStr, - after, - nested - }) +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); } else { - o[strPath] = { - path: path, - val: undefined, - precensored: false, - circle: '', - escPath: JSON.stringify(strPath), - leadingBracket: leadingBracket - } + ret.params[pms[0]] = pms[1]; } - return o - }, {}) + } - return { wildcards, wcLen, secret } + return ret; } +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ -/***/ }), +exports.compileETag = function(val) { + var fn; -/***/ 17333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof val === 'function') { + return val; + } -"use strict"; + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + return fn; +} -const rx = __nccwpck_require__(9158) +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ -module.exports = redactor +exports.compileQueryParser = function compileQueryParser(val) { + var fn; -function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { - /* eslint-disable-next-line */ - const redact = Function('o', ` - if (typeof o !== 'object' || o == null) { - ${strictImpl(strict, serialize)} - } - const { censor, secret } = this - ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} - this.compileRestore() - ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} - ${resultTmpl(serialize)} - `).bind(state) + if (typeof val === 'function') { + return val; + } - if (serialize === false) { - redact.restore = (o) => state.restore(o) + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); } - return redact + return fn; } -function redactTmpl (secret, isCensorFct, censorFctTakesPath) { - return Object.keys(secret).map((path) => { - const { escPath, leadingBracket, path: arrPath } = secret[path] - const skip = leadingBracket ? 1 : 0 - const delim = leadingBracket ? '' : '.' - const hops = [] - var match - while ((match = rx.exec(path)) !== null) { - const [ , ix ] = match - const { index, input } = match - if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) - } - var existence = hops.map((p) => `o${delim}${p}`).join(' && ') - if (existence.length === 0) existence += `o${delim}${path} != null` - else existence += ` && o${delim}${path} != null` - - const circularDetection = ` - switch (true) { - ${hops.reverse().map((p) => ` - case o${delim}${p} === censor: - secret[${escPath}].circle = ${JSON.stringify(p)} - break - `).join('\n')} - } - ` +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ - const censorArgs = censorFctTakesPath - ? `val, ${JSON.stringify(arrPath)}` - : `val` +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; - return ` - if (${existence}) { - const val = o${delim}${path} - if (val === censor) { - secret[${escPath}].precensored = true - } else { - secret[${escPath}].val = val - o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} - ${circularDetection} - } - } - ` - }).join('\n') -} + if (val === true) { + // Support plain true/false + return function(){ return true }; + } -function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { - return hasWildcards === true ? ` - { - const { wildcards, wcLen, groupRedact, nestedRedact } = this - for (var i = 0; i < wcLen; i++) { - const { before, beforeStr, after, nested } = wildcards[i] - if (nested === true) { - secret[beforeStr] = secret[beforeStr] || [] - nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) - } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) - } - } - ` : '' -} + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } -function resultTmpl (serialize) { - return serialize === false ? `return o` : ` - var s = this.serialize(o) - this.restore(o) - return s - ` -} + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } -function strictImpl (strict, serialize) { - return strict === true - ? `throw Error('fast-redact: primitives cannot be redacted')` - : serialize === false ? `return o` : `return this.serialize(o)` + return proxyaddr.compile(val || []); } +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ -/***/ }), +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } -/***/ 98806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // parse type + var parsed = contentType.parse(type); -"use strict"; + // set charset + parsed.parameters.charset = charset; + // format type + return contentType.format(parsed); +}; -const { groupRestore, nestedRestore } = __nccwpck_require__(54865) +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ -module.exports = restorer +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body -function restorer ({ secret, wcLen }) { - return function compileRestore () { - if (this.restore) return - const paths = Object.keys(secret) - .filter((path) => secret[path].precensored === false) - const resetters = resetTmpl(secret, paths) - const hasWildcards = wcLen > 0 - const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } - /* eslint-disable-next-line */ - this.restore = Function( - 'o', - restoreTmpl(resetters, paths, hasWildcards) - ).bind(state) + return etag(buf, options) } } /** - * Mutates the original object to be censored by restoring its original values - * prior to censoring. + * Parse an extended query string with qs. * - * @param {object} secret Compiled object describing which target fields should - * be censored and the field states. - * @param {string[]} paths The list of paths to censor as provided at - * initialization time. + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. * - * @returns {string} String of JavaScript to be used by `Function()`. The - * string compiles to the function that does the work in the description. + * @return {Object} + * @api private */ -function resetTmpl (secret, paths) { - return paths.map((path) => { - const { circle, escPath, leadingBracket } = secret[path] - const delim = leadingBracket ? '' : '.' - const reset = circle - ? `o.${circle} = secret[${escPath}].val` - : `o${delim}${path} = secret[${escPath}].val` - const clear = `secret[${escPath}].val = undefined` - return ` - if (secret[${escPath}].val !== undefined) { - try { ${reset} } catch (e) {} - ${clear} - } - ` - }).join('') -} - -function restoreTmpl (resetters, paths, hasWildcards) { - const dynamicReset = hasWildcards === true ? ` - const keys = Object.keys(secret) - const len = keys.length - for (var i = ${paths.length}; i < len; i++) { - const k = keys[i] - const o = secret[k] - if (o.flat === true) this.groupRestore(o) - else this.nestedRestore(o) - secret[k] = null - } - ` : '' - - return ` - const secret = this.secret - ${resetters} - ${dynamicReset} - return o - ` + +function newObject() { + return {}; } /***/ }), -/***/ 9158: -/***/ ((module) => { +/***/ 99209: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -module.exports = /[^.[\]]+|\[((?:.)*?)\]/g -/* -Regular expression explanation: +/** + * Module dependencies. + * @private + */ -Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) - opening square bracket ([) or closing square bracket (]) +var debug = __nccwpck_require__(52529)('express:view'); +var path = __nccwpck_require__(85622); +var fs = __nccwpck_require__(35747); -Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture - group (which will be capture group $1) that matches anything - within square brackets. Expansion is lazy so it will - stop matching as soon as the first closing bracket is met `]` - (rather than continuing to match until the final closing bracket). -*/ +/** + * Module variables. + * @private + */ +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; -/***/ }), +/** + * Module exports. + * @public + */ -/***/ 41012: -/***/ ((module) => { +module.exports = View; -"use strict"; +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ +function View(name, options) { + var opts = options || {}; -module.exports = state + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; -function state (o) { - const { - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - } = o - const builder = [{ secret, censor, compileRestore }] - if (serialize !== false) builder.push({ serialize }) - if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) - return Object.assign(...builder) -} + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + var fileName = name; -/***/ }), + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; -/***/ 74174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + fileName += this.ext; + } -"use strict"; + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) + // default engine export + var fn = require(mod).__express -const { createContext, runInContext } = __nccwpck_require__(92184) + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } -module.exports = validator + opts.engines[this.ext] = fn + } -function validator (opts = {}) { - const { - ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', - ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` - } = opts + // store loaded engine + this.engine = opts.engines[this.ext]; - return function validate ({ paths }) { - paths.forEach((s) => { - if (typeof s !== 'string') { - throw Error(ERR_PATHS_MUST_BE_STRINGS()) - } - try { - if (/〇/.test(s)) throw Error() - const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) - const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') - if (/\n|\r|;/.test(expr)) throw Error() - if (/\/\*/.test(expr)) throw Error() - runInContext(` - (function () { - 'use strict' - o${expr} - if ([o${expr}].length !== 1) throw Error() - })() - `, createContext({ o: proxy, 〇: null }), { - codeGeneration: { strings: false, wasm: false } - }) - } catch (e) { - throw Error(ERR_INVALID_PATH(s)) - } - }) - } + // lookup path + this.path = this.lookup(fileName); } +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ -/***/ }), +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); -/***/ 17676: -/***/ ((module) => { + debug('lookup "%s"', name); -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; -var arr = [] -var replacerStack = [] + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); -// Regular stringify -function stringify (obj, replacer, spacer) { - decirc(obj, '', [], undefined) - var res - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer) - } else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) - } - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - return res -} -function decirc (val, k, stack, parent) { - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: '[Circular]' }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k]) - } - } else { - parent[k] = '[Circular]' - arr.push([parent, k, val]) - } - return - } - } - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, stack, val) - } - } else { - var keys = Object.keys(val) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - decirc(val[key], key, stack, val) - } - } - stack.pop() + // resolve the file + path = this.resolve(dir, file); } -} -// Stable-stringify -function compareFunction (a, b) { - if (a < b) { - return -1 - } - if (a > b) { - return 1 - } - return 0 -} + return path; +}; -function deterministicStringify (obj, replacer, spacer) { - var tmp = deterministicDecirc(obj, '', [], undefined) || obj - var res - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer) - } else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) - } - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; } - return res -} -function deterministicDecirc (val, k, stack, parent) { - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: '[Circular]' }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k]) - } - } else { - parent[k] = '[Circular]' - arr.push([parent, k, val]) - } - return - } - } - if (typeof val.toJSON === 'function') { - return - } - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, stack, val) - } - } else { - // Create a temporary object in the required way - var tmp = {} - var keys = Object.keys(val).sort(compareFunction) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - deterministicDecirc(val[key], key, stack, val) - tmp[key] = val[key] - } - if (parent !== undefined) { - arr.push([parent, k, val]) - parent[k] = tmp - } else { - return tmp - } - } - stack.pop() + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; } -} +}; -// wraps replacer function to handle values we couldn't replace -// and mark them as [Circular] -function replaceGetterValues (replacer) { - replacer = replacer !== undefined ? replacer : function (k, v) { return v } - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i] - if (part[1] === key && part[0] === val) { - val = '[Circular]' - replacerStack.splice(i, 1) - break - } - } - } - return replacer.call(this, key, val) +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; } } /***/ }), -/***/ 34578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 66515: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -/* -Copyright (c) 2014 Petka Antonov -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. +/** + * Module exports. + * @public + */ -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 Url() { - //For more efficient internal representation and laziness. - //The non-underscore versions of these properties are accessor functions - //defined on the prototype. - this._protocol = null; - this._href = ""; - this._port = -1; - this._query = null; +exports.parse = parse; +exports.serialize = serialize; - this.auth = null; - this.slashes = null; - this.host = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; +/** + * Module variables. + * @private + */ - this._prependSlash = false; -} +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; -var querystring = __nccwpck_require__(71191); +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ -Url.queryString = querystring; +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; -Url.prototype.parse = -function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (typeof str !== "string") { - throw new TypeError("Parameter 'url' must be a string, not " + - typeof str); - } - var start = 0; - var end = str.length - 1; +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ - //Trim leading and trailing ws - while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; - while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } - start = this._parseProtocol(str, start, end); + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; - //Javascript doesn't have host - if (this._protocol !== "javascript") { - start = this._parseHost(str, start, end, hostDenotesSlash); - var proto = this._protocol; - if (!this.hostname && - (this.slashes || (proto && !slashProtocols[proto]))) { - this.hostname = this.host = ""; - } + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); + + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; } - if (start <= end) { - var ch = str.charCodeAt(start); - - if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x23 /*'#'*/) { - this._parseHash(str, start, end, disableAutoEscapeChars); - } - else if (this._protocol !== "javascript") { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else { //For javascript the pathname is just the rest of it - this.pathname = str.slice(start, end + 1 ); - } + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); } - if (!this.pathname && this.hostname && - this._slashProtocols[this._protocol]) { - this.pathname = "/"; + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); } + } - if (parseQueryString) { - var search = this.search; - if (search == null) { - search = this.search = ""; - } - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - //This calls a setter function, there is no .query data property - this.query = Url.queryString.parse(search); - } -}; + return obj; +} -Url.prototype.resolve = function Url$resolve(relative) { - return this.resolveObject(Url.parse(relative, false, true)).format(); -}; +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ -Url.prototype.format = function Url$format() { - var auth = this.auth || ""; +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ":"); - auth += "@"; - } + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } - var protocol = this.protocol || ""; - var pathname = this.pathname || ""; - var hash = this.hash || ""; - var search = this.search || ""; - var query = ""; - var hostname = this.hostname || ""; - var port = this.port || ""; - var host = false; - var scheme = ""; + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } - //Cache the result of the getter function - var q = this.query; - if (q && typeof q === "object") { - query = Url.queryString.stringify(q); - } + var value = enc(val); - if (!search) { - search = query ? "?" + query : ""; - } + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } - if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) - protocol += ":"; + var str = name + '=' + value; - if (this.host) { - host = auth + this.host; - } - else if (hostname) { - var ip6 = hostname.indexOf(":") > -1; - if (ip6) hostname = "[" + hostname + "]"; - host = auth + hostname + (port ? ":" + port : ""); + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); } - var slashes = this.slashes || - ((!protocol || - slashProtocols[protocol]) && host !== false); + str += '; Domain=' + opt.domain; + } + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } - if (protocol) scheme = protocol + (slashes ? "//" : ""); - else if (slashes) scheme = "//"; + str += '; Path=' + opt.path; + } - if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { - pathname = "/" + pathname; + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); } - if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) - search = "?" + search; - if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) - hash = "#" + hash; - - pathname = escapePathName(pathname); - search = escapeSearch(search); - return scheme + (host === false ? "" : host) + pathname + search + hash; -}; + str += '; Expires=' + opt.expires.toUTCString(); + } -Url.prototype.resolveObject = function Url$resolveObject(relative) { - if (typeof relative === "string") - relative = Url.parse(relative, false, true); + if (opt.httpOnly) { + str += '; HttpOnly'; + } - var result = this._clone(); + if (opt.secure) { + str += '; Secure'; + } - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; - // if the relative url is empty, then there"s nothing left to do here. - if (!relative.href) { - result._href = ""; - return result; + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); } + } - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative._protocol) { - relative._copyPropsTo(result, true); - - if (slashProtocols[result._protocol] && - result.hostname && !result.pathname) { - result.pathname = "/"; - } - result._href = ""; - return result; - } + return str; +} - if (relative._protocol && relative._protocol !== result._protocol) { - // if it"s a known url protocol, then changing - // the protocol does weird things - // first, if it"s not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that"s known to be hostless. - // anything else is assumed to be absolute. - if (!slashProtocols[relative._protocol]) { - relative._copyPropsTo(result, false); - result._href = ""; - return result; - } +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ - result._protocol = relative._protocol; - if (!relative.host && relative._protocol !== "javascript") { - var relPath = (relative.pathname || "").split("/"); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ""; - if (!relative.hostname) relative.hostname = ""; - if (relPath[0] !== "") relPath.unshift(""); - if (relPath.length < 2) relPath.unshift(""); - result.pathname = relPath.join("/"); - } else { - result.pathname = relative.pathname; - } +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} - result.search = relative.search; - result.host = relative.host || ""; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result._port = relative._port; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; - } - var isSourceAbs = - (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/); - var isRelAbs = ( - relative.host || - (relative.pathname && - relative.pathname.charCodeAt(0) === 0x2F /*'/'*/) - ); - var mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)); +/***/ }), - var removeAllDots = mustEndAbs; +/***/ 36654: +/***/ ((module, exports, __nccwpck_require__) => { - var srcPath = result.pathname && result.pathname.split("/") || []; - var relPath = relative.pathname && relative.pathname.split("/") || []; - var psychotic = result._protocol && !slashProtocols[result._protocol]; +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ""; - result._port = -1; - if (result.host) { - if (srcPath[0] === "") srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ""; - if (relative._protocol) { - relative.hostname = ""; - relative._port = -1; - if (relative.host) { - if (relPath[0] === "") relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = ""; - } - mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); - } +exports = module.exports = __nccwpck_require__(86991); +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(); - if (isRelAbs) { - // it"s absolute. - result.host = relative.host ? - relative.host : result.host; - result.hostname = relative.hostname ? - relative.hostname : result.hostname; - result.search = relative.search; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it"s relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - } else if (relative.search) { - // just pull out the search. - // like href="?foo". - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var authInHost = result.host && result.host.indexOf("@") > 0 ? - result.host.split("@") : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result._href = ""; - return result; - } +/** + * Colors. + */ - if (!srcPath.length) { - // no path at all. easy. - // we"ve already handled the other stuff above. - result.pathname = null; - result._href = ""; - return result; - } +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host) && (last === "." || last === "..") || - last === ""); +/** + * 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 + */ - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === ".") { - srcPath.splice(i, 1); - } else if (last === "..") { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } +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 the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift(".."); - } - } + // 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+)/)); +} - if (mustEndAbs && srcPath[0] !== "" && - (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { - srcPath.unshift(""); - } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { - srcPath.push(""); - } +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; - var isAbsolute = srcPath[0] === "" || - (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? "" : - srcPath.length ? srcPath.shift() : ""; - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var authInHost = result.host && result.host.indexOf("@") > 0 ? - result.host.split("@") : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } +/** + * Colorize log arguments if enabled. + * + * @api public + */ - mustEndAbs = mustEndAbs || (result.host && srcPath.length); +function formatArgs(args) { + var useColors = this.useColors; - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(""); - } + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; -}; + if (!useColors) return; -var punycode = __nccwpck_require__(94213); -Url.prototype._hostIdna = function Url$_hostIdna(hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - return punycode.toASCII(hostname); -}; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') -var escapePathName = Url.prototype._escapePathName = -function Url$_escapePathName(pathname) { - if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { - return pathname; + // 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; } - //Avoid closure creation to keep this inlinable - return _escapePath(pathname); -}; + }); -var escapeSearch = Url.prototype._escapeSearch = -function Url$_escapeSearch(search) { - if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search; - //Avoid closure creation to keep this inlinable - return _escapeSearch(search); -}; + args.splice(lastC, 0, c); +} -Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { - var doLowerCase = false; - var protocolCharacters = this._protocolCharacters; +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +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); +} - if (ch === 0x3A /*':'*/) { - var protocol = str.slice(start, i); - if (doLowerCase) protocol = protocol.toLowerCase(); - this._protocol = protocol; - return i + 1; - } - else if (protocolCharacters[ch] === 1) { - if (ch < 0x61 /*'a'*/) - doLowerCase = true; - } - else { - return start; - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; } - return start; -}; + } catch(e) {} +} -Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) { - var auth = str.slice(start, end + 1); - if (decode) { - auth = decodeURIComponent(auth); - } - this.auth = auth; -}; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -Url.prototype._parsePort = function Url$_parsePort(str, start, end) { - //Internal format is integer for more efficient parsing - //and for efficient trimming of leading zeros - var port = 0; - //Distinguish between :0 and : (no port number at all) - var hadChars = false; - var validPort = true; +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + // 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; + } - if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) { - port = (10 * port) + (ch - 0x30 /*'0'*/); - hadChars = true; - } - else { - validPort = false; - if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) { - validPort = true; - } - break; - } + return r; +} - } - if ((port === 0 && !hadChars) || !validPort) { - if (!validPort) { - this._port = -2; - } - return 0; - } +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - this._port = port; - return i - start; -}; +exports.enable(load()); -Url.prototype._parseHost = -function Url$_parseHost(str, start, end, slashesDenoteHost) { - var hostEndingCharacters = this._hostEndingCharacters; - var first = str.charCodeAt(start); - var second = str.charCodeAt(start + 1); - if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) && - (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) { - this.slashes = true; +/** + * 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 + */ - //The string starts with // - if (start === 0) { - //The string is just "//" - if (end < 2) return start; - //If slashes do not denote host and there is no auth, - //there is no host when the string starts with // - var hasAuth = - containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters); - if (!hasAuth && !slashesDenoteHost) { - this.slashes = null; - return start; - } - } - //There is a host that starts after the // - start += 2; - } - //If there is no slashes, there is no hostname if - //1. there was no protocol at all - else if (!this._protocol || - //2. there was a protocol that requires slashes - //e.g. in 'http:asd' 'asd' is not a hostname - slashProtocols[this._protocol] - ) { - return start; - } +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} - var doLowerCase = false; - var idna = false; - var hostNameStart = start; - var hostNameEnd = end; - var lastCh = -1; - var portLength = 0; - var charsAfterDot = 0; - var authNeedsDecoding = false; - var j = -1; +/***/ }), - //Find the last occurrence of an @-sign until hostending character is met - //also mark if decoding is needed for the auth portion - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +/***/ 86991: +/***/ ((module, exports, __nccwpck_require__) => { - if (ch === 0x40 /*'@'*/) { - j = i; - } - //This check is very, very cheap. Unneeded decodeURIComponent is very - //very expensive - else if (ch === 0x25 /*'%'*/) { - authNeedsDecoding = true; - } - else if (hostEndingCharacters[ch] === 1) { - break; - } - } - //@-sign was found at index j, everything to the left from it - //is auth part - if (j > -1) { - this._parseAuth(str, start, j - 1, authNeedsDecoding); - //hostname starts after the last @-sign - start = hostNameStart = j + 1; - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - //Host name is starting with a [ - if (str.charCodeAt(start) === 0x5B /*'['*/) { - for (var i = start + 1; i <= end; ++i) { - var ch = str.charCodeAt(i); +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(27025); - //Assume valid IP6 is between the brackets - if (ch === 0x5D /*']'*/) { - if (str.charCodeAt(i + 1) === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 2, end) + 1; - } - var hostname = str.slice(start + 1, i).toLowerCase(); - this.hostname = hostname; - this.host = this._port > 0 ? - "[" + hostname + "]:" + this._port : - "[" + hostname + "]"; - this.pathname = "/"; - return i + portLength + 1; - } - } - //Empty hostname, [ starts a path - return start; - } +/** + * The currently active debug mode names, and names to skip. + */ - for (var i = start; i <= end; ++i) { - if (charsAfterDot > 62) { - this.hostname = this.host = str.slice(start, i); - return i; - } - var ch = str.charCodeAt(i); +exports.names = []; +exports.skips = []; - if (ch === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 1, end) + 1; - hostNameEnd = i - 1; - break; - } - else if (ch < 0x61 /*'a'*/) { - if (ch === 0x2E /*'.'*/) { - //Node.js ignores this error - /* - if (lastCh === DOT || lastCh === -1) { - this.hostname = this.host = ""; - return start; - } - */ - charsAfterDot = -1; - } - else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { - doLowerCase = true; - } - //Valid characters other than ASCII letters -, _, +, 0-9 - else if (!(ch === 0x2D /*'-'*/ || - ch === 0x5F /*'_'*/ || - ch === 0x2B /*'+'*/ || - (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/)) - ) { - if (hostEndingCharacters[ch] === 0 && - this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - } - else if (ch >= 0x7B /*'{'*/) { - if (ch <= 0x7E /*'~'*/) { - if (this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - idna = true; - } - lastCh = ch; - charsAfterDot++; - } +/** + * 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". + */ - //Node.js ignores this error - /* - if (lastCh === DOT) { - hostNameEnd--; - } - */ +exports.formatters = {}; - if (hostNameEnd + 1 !== start && - hostNameEnd - hostNameStart <= 256) { - var hostname = str.slice(hostNameStart, hostNameEnd + 1); - if (doLowerCase) hostname = hostname.toLowerCase(); - if (idna) hostname = this._hostIdna(hostname); - this.hostname = hostname; - this.host = this._port > 0 ? hostname + ":" + this._port : hostname; - } +/** + * Previous log timestamp. + */ - return hostNameEnd + 1 + portLength; +var prevTime; -}; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { - if (!noProtocol) { - input._protocol = this._protocol; - } - input._href = this._href; - input._port = this._port; - input._prependSlash = this._prependSlash; - input.auth = this.auth; - input.slashes = this.slashes; - input.host = this.host; - input.hostname = this.hostname; - input.hash = this.hash; - input.search = this.search; - input.pathname = this.pathname; -}; +function selectColor(namespace) { + var hash = 0, i; -Url.prototype._clone = function Url$_clone() { - var ret = new Url(); - ret._protocol = this._protocol; - ret._href = this._href; - ret._port = this._port; - ret._prependSlash = this._prependSlash; - ret.auth = this.auth; - ret.slashes = this.slashes; - ret.host = this.host; - ret.hostname = this.hostname; - ret.hash = this.hash; - ret.search = this.search; - ret.pathname = this.pathname; - return ret; -}; + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -Url.prototype._getComponentEscaped = -function Url$_getComponentEscaped(str, start, end, isAfterQuery) { - var cur = start; - var i = start; - var ret = ""; - var autoEscapeMap = isAfterQuery ? - this._afterQueryAutoEscapeMap : this._autoEscapeMap; - for (; i <= end; ++i) { - var ch = str.charCodeAt(i); - var escaped = autoEscapeMap[ch]; + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - if (escaped !== "" && escaped !== undefined) { - if (cur < i) ret += str.slice(cur, i); - ret += escaped; - cur = i + 1; - } - } - if (cur < i + 1) ret += str.slice(cur, i); - return ret; -}; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -Url.prototype._parsePath = -function Url$_parsePath(str, start, end, disableAutoEscapeChars) { - var pathStart = start; - var pathEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; - var prePath = this._port === -2 ? "/:" : ""; +function createDebug(namespace) { - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } + function debug() { + // disabled? + if (!debug.enabled) return; - if (pathStart > pathEnd) { - this.pathname = prePath === "" ? "/" : prePath; - return; - } + var self = debug; - var path; - if (escape) { - path = this._getComponentEscaped(str, pathStart, pathEnd, false); + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // 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]; } - else { - path = str.slice(pathStart, pathEnd + 1); + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - this.pathname = prePath === "" - ? (this._prependSlash ? "/" + path : path) - : prePath + path; -}; -Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { - var queryStart = start; - var queryEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; + // 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); - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - queryEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); - if (queryStart > queryEnd) { - this.search = ""; - return; - } + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } - var query; - if (escape) { - query = this._getComponentEscaped(str, queryStart, queryEnd, true); - } - else { - query = str.slice(queryStart, queryEnd + 1); - } - this.search = query; -}; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { - if (start > end) { - this.hash = ""; - return; - } + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } - this.hash = disableAutoEscapeChars ? - str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); -}; + return debug; +} -Object.defineProperty(Url.prototype, "port", { - get: function() { - if (this._port >= 0) { - return ("" + this._port); - } - return null; - }, - set: function(v) { - if (v == null) { - this._port = -1; - } - else { - this._port = parseInt(v, 10); - } - } -}); +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ -Object.defineProperty(Url.prototype, "query", { - get: function() { - var query = this._query; - if (query != null) { - return query; - } - var search = this.search; +function enable(namespaces) { + exports.save(namespaces); - if (search) { - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - if (search !== "") { - this._query = search; - return search; - } - } - return search; - }, - set: function(v) { - this._query = v; - } -}); - -Object.defineProperty(Url.prototype, "path", { - get: function() { - var p = this.pathname || ""; - var s = this.search || ""; - if (p || s) { - return p + s; - } - return (p == null && s) ? ("/" + s) : null; - }, - set: function() {} -}); - -Object.defineProperty(Url.prototype, "protocol", { - get: function() { - var proto = this._protocol; - return proto ? proto + ":" : proto; - }, - set: function(v) { - if (typeof v === "string") { - var end = v.length - 1; - if (v.charCodeAt(end) === 0x3A /*':'*/) { - this._protocol = v.slice(0, end); - } - else { - this._protocol = v; - } - } - else if (v == null) { - this._protocol = null; - } - } -}); - -Object.defineProperty(Url.prototype, "href", { - get: function() { - var href = this._href; - if (!href) { - href = this._href = this.format(); - } - return href; - }, - set: function(v) { - this._href = v; - } -}); + exports.names = []; + exports.skips = []; -Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (str instanceof Url) return str; - var ret = new Url(); - ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars); - return ret; -}; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; -Url.format = function Url$Format(obj) { - if (typeof obj === "string") { - obj = Url.parse(obj); - } - if (!(obj instanceof Url)) { - return Url.prototype.format.call(obj); + 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 + '$')); } - return obj.format(); -}; - -Url.resolve = function Url$Resolve(source, relative) { - return Url.parse(source, false, true).resolve(relative); -}; - -Url.resolveObject = function Url$ResolveObject(source, relative) { - if (!source) return relative; - return Url.parse(source, false, true).resolveObject(relative); -}; - -function _escapePath(pathname) { - return pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); + } } -function _escapeSearch(search) { - return search.replace(/#/g, function(match) { - return encodeURIComponent(match); - }); +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); } -//Search `char1` (integer code for a character) in `string` -//starting from `fromIndex` and ending at `string.length - 1` -//or when a stop character is found -function containsCharacter(string, char1, fromIndex, stopCharacterTable) { - var len = string.length; - for (var i = fromIndex; i < len; ++i) { - var ch = string.charCodeAt(i); +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - if (ch === char1) { - return true; - } - else if (stopCharacterTable[ch] === 1) { - return false; - } +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; } - return false; -} - -//See if `char1` or `char2` (integer codes for characters) -//is contained in `string` -function containsCharacter2(string, char1, char2) { - for (var i = 0, len = string.length; i < len; ++i) { - var ch = string.charCodeAt(i); - if (ch === char1 || ch === char2) return true; + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } - return false; + } + return false; } -//Makes an array of 128 uint8's which represent boolean values. -//Spec is an array of ascii code points or ascii code point ranges -//ranges are expressed as [start, end] - -//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and -//0x7A (lowercaseletter 'z') as `true`: -// -//var a = makeAsciiTable([[0x30, 0x39], 0x7A]); -//a[0x30]; //1 -//a[0x15]; //0 -//a[0x35]; //1 -function makeAsciiTable(spec) { - var ret = new Uint8Array(128); - spec.forEach(function(item){ - if (typeof item === "number") { - ret[item] = 1; - } - else { - var start = item[0]; - var end = item[1]; - for (var j = start; j <= end; ++j) { - ret[j] = 1; - } - } - }); +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - return ret; +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; } -var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", - "\t", "{", "}", "|", "\\", "^", "`", "'"]; - -var autoEscapeMap = new Array(128); - +/***/ }), +/***/ 52529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { - autoEscapeMap[i] = ""; -} +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ -for (var i = 0, len = autoEscape.length; i < len; ++i) { - var c = autoEscape[i]; - var esc = encodeURIComponent(c); - if (esc === c) { - esc = escape(c); - } - autoEscapeMap[c.charCodeAt(0)] = esc; +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(36654); +} else { + module.exports = __nccwpck_require__(25696); } -var afterQueryAutoEscapeMap = autoEscapeMap.slice(); -autoEscapeMap[0x5C /*'\'*/] = "/"; - -var slashProtocols = Url.prototype._slashProtocols = { - http: true, - https: true, - gopher: true, - file: true, - ftp: true, - - "http:": true, - "https:": true, - "gopher:": true, - "file:": true, - "ftp:": true -}; - -//Optimize back from normalized object caused by non-identifier keys -function f(){} -f.prototype = slashProtocols; - -Url.prototype._protocolCharacters = makeAsciiTable([ - [0x61 /*'a'*/, 0x7A /*'z'*/], - [0x41 /*'A'*/, 0x5A /*'Z'*/], - 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ -]); - -Url.prototype._hostEndingCharacters = makeAsciiTable([ - 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ -]); - -Url.prototype._autoEscapeCharacters = makeAsciiTable( - autoEscape.map(function(v) { - return v.charCodeAt(0); - }) -); - -//If these characters end a host name, the path will not be prepended a / -Url.prototype._noPrependSlashHostEnders = makeAsciiTable( - [ - "<", ">", "'", "`", " ", "\r", - "\n", "\t", "{", "}", "|", - "^", "`", "\"", "%", ";" - ].map(function(v) { - return v.charCodeAt(0); - }) -); - -Url.prototype._autoEscapeMap = autoEscapeMap; -Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; - -module.exports = Url; - -Url.replace = function Url$Replace() { - require.cache.url = { - exports: Url - }; -}; /***/ }), -/***/ 30810: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 25696: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * finalhandler - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed +/** + * Module dependencies. */ - +var tty = __nccwpck_require__(33867); +var util = __nccwpck_require__(31669); /** - * Module dependencies. - * @private + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. */ -var debug = __nccwpck_require__(65612)('finalhandler') -var encodeUrl = __nccwpck_require__(16592) -var escapeHtml = __nccwpck_require__(94070) -var onFinished = __nccwpck_require__(92098) -var parseUrl = __nccwpck_require__(89808) -var statuses = __nccwpck_require__(57415) -var unpipe = __nccwpck_require__(3124) +exports = module.exports = __nccwpck_require__(86991); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; /** - * Module variables. - * @private + * Colors. */ -var DOUBLE_SPACE_REGEXP = /\x20{2}/g -var NEWLINE_REGEXP = /\n/g - -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } -var isFinished = onFinished.isFinished +exports.colors = [6, 2, 3, 4, 5, 1]; /** - * Create a minimal HTML document. + * Build up the default `inspectOpts` object from the environment variables. * - * @param {string} message - * @private + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -function createHtmlDocument (message) { - var body = escapeHtml(message) - .replace(NEWLINE_REGEXP, '
') - .replace(DOUBLE_SPACE_REGEXP, '  ') - - return '\n' + - '\n' + - '\n' + - '\n' + - 'Error\n' + - '\n' + - '\n' + - '
' + body + '
\n' + - '\n' + - '\n' -} +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); -/** - * Module exports. - * @public - */ + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); -module.exports = finalhandler + obj[prop] = val; + return obj; +}, {}); /** - * Create a function to handle the final response. + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: * - * @param {Request} req - * @param {Response} res - * @param {Object} [options] - * @return {Function} - * @public + * $ DEBUG_FD=3 node script.js 3>debug.log */ -function finalhandler (req, res, options) { - var opts = options || {} - - // get environment - var env = opts.env || process.env.NODE_ENV || 'development' - - // get error callback - var onerror = opts.onerror - - return function (err) { - var headers - var msg - var status +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - // ignore 404 on in-flight response - if (!err && headersSent(res)) { - debug('cannot 404 after headers sent') - return - } +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} - // unhandled error - if (err) { - // respect status code from error - status = getErrorStatusCode(err) +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - if (status === undefined) { - // fallback to status code on response - status = getResponseStatusCode(res) - } else { - // respect headers from error - headers = getErrorHeaders(err) - } +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - // get error message - msg = getErrorMessage(err, status, env) - } else { - // not found - status = 404 - msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) - } +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} - debug('default %s', status) +/** + * Map %o to `util.inspect()`, all on a single line. + */ - // schedule onerror callback - if (err && onerror) { - defer(onerror, err, req, res) - } +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; - // cannot actually respond - if (headersSent(res)) { - debug('cannot %d after headers sent', status) - req.socket.destroy() - return - } +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - // send response - send(req, res, status, headers, msg) - } -} +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /** - * Get headers from Error object. + * Adds ANSI color escape codes if enabled. * - * @param {Error} err - * @return {object} - * @private + * @api public */ -function getErrorHeaders (err) { - if (!err.headers || typeof err.headers !== 'object') { - return undefined - } +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - var headers = Object.create(null) - var keys = Object.keys(err.headers) + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - headers[key] = err.headers[key] + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } - - return headers } /** - * Get message from Error object, fallback to status message. - * - * @param {Error} err - * @param {number} status - * @param {string} env - * @return {string} - * @private + * Invokes `util.format()` with the specified arguments and writes to `stream`. */ -function getErrorMessage (err, status, env) { - var msg - - if (env !== 'production') { - // use err.stack, which typically includes err.message - msg = err.stack - - // fallback to err.toString() when possible - if (!msg && typeof err.toString === 'function') { - msg = err.toString() - } - } - - return msg || statuses[status] +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); } /** - * Get status code from Error object. + * Save `namespaces`. * - * @param {Error} err - * @return {number} - * @private + * @param {String} namespaces + * @api private */ -function getErrorStatusCode (err) { - // check err.status - if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { - return err.status - } - - // check err.statusCode - if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode - } - - return undefined -} - -/** - * Get resource name for the request. - * - * This is typically just the original pathname of the request - * but will fallback to "resource" is that cannot be determined. - * - * @param {IncomingMessage} req - * @return {string} - * @private - */ - -function getResourceName (req) { - try { - return parseUrl.original(req).pathname - } catch (e) { - return 'resource' +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; } } /** - * Get status code from response. + * Load `namespaces`. * - * @param {OutgoingMessage} res - * @return {number} - * @private + * @return {String} returns the previously persisted debug modes + * @api private */ -function getResponseStatusCode (res) { - var status = res.statusCode - - // default status code to 500 if outside valid range - if (typeof status !== 'number' || status < 400 || status > 599) { - status = 500 - } - - return status +function load() { + return process.env.DEBUG; } /** - * Determine if the response headers have been sent. + * Copied from `node/src/node.js`. * - * @param {object} res - * @returns {boolean} - * @private + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. */ -function headersSent (res) { - return typeof res.headersSent !== 'boolean' - ? Boolean(res._header) - : res.headersSent -} +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); -/** - * Send response. - * - * @param {IncomingMessage} req - * @param {OutgoingMessage} res - * @param {number} status - * @param {object} headers - * @param {string} message - * @private - */ + // Note stream._type is used for test-module-load-list.js -function send (req, res, status, headers, message) { - function write () { - // response body - var body = createHtmlDocument(message) + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - // response status - res.statusCode = status - res.statusMessage = statuses[status] + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - // response headers - setHeaders(res, headers) + case 'FILE': + var fs = __nccwpck_require__(35747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; - // security headers - res.setHeader('Content-Security-Policy', "default-src 'none'") - res.setHeader('X-Content-Type-Options', 'nosniff') + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(11631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - // standard headers - res.setHeader('Content-Type', 'text/html; charset=utf-8') - res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; - if (req.method === 'HEAD') { - res.end() - return - } + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - res.end(body, 'utf8') + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } - if (isFinished(req)) { - write() - return - } + // For supporting legacy API we put the FD here. + stream.fd = fd; - // unpipe everything from the request - unpipe(req) + stream._isStdio = true; - // flush the request - onFinished(req, write) - req.resume() + return stream; } /** - * Set response headers from an object. + * Init logic for `debug` instances. * - * @param {OutgoingMessage} res - * @param {object} headers - * @private + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function setHeaders (res, headers) { - if (!headers) { - return - } +function init (debug) { + debug.inspectOpts = {}; - var keys = Object.keys(headers) + var keys = Object.keys(exports.inspectOpts); for (var i = 0; i < keys.length; i++) { - var key = keys[i] - res.setHeader(key, headers[key]) + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } - -/***/ }), - -/***/ 56401: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = __nccwpck_require__(60545); -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(); - /** - * Colors. + * Enable namespaces listed in `process.env.DEBUG` initially. */ -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +exports.enable(load()); -/** - * 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 - */ -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; - } +/***/ }), - // 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+)/)); -} +/***/ 27025: +/***/ ((module) => { /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * Helpers. */ -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; /** - * Colorize log arguments if enabled. + * Parse or format the given `val`. * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // 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; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". + * Options: + * + * - `long` verbose formatting [false] * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} * @api public */ -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); -} +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; /** - * Save `namespaces`. + * Parse the given `str` and return milliseconds. * - * @param {String} namespaces + * @param {String} str + * @return {Number} * @api private */ -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } } /** - * Load `namespaces`. + * Short format for `ms`. * - * @return {String} returns the previously persisted debug modes + * @param {Number} ms + * @return {String} * @api private */ -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // 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; +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; } - - return r; + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } /** - * Enable namespaces listed in `localStorage.debug` initially. + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private */ -exports.enable(load()); +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} /** - * 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 + * Pluralization helper. */ -function localstorage() { - try { - return window.localStorage; - } catch (e) {} +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }), -/***/ 60545: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 24826: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(80761); +const validator = __nccwpck_require__(74174) +const parse = __nccwpck_require__(96214) +const redactor = __nccwpck_require__(17333) +const restorer = __nccwpck_require__(98806) +const { groupRedact, nestedRedact } = __nccwpck_require__(54865) +const state = __nccwpck_require__(41012) +const rx = __nccwpck_require__(9158) +const validate = validator() +const noop = (o) => o +noop.restore = noop -/** - * The currently active debug mode names, and names to skip. - */ +const DEFAULT_CENSOR = '[REDACTED]' +fastRedact.rx = rx +fastRedact.validator = validator -exports.names = []; -exports.skips = []; +module.exports = fastRedact -/** - * 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". - */ +function fastRedact (opts = {}) { + const paths = Array.from(new Set(opts.paths || [])) + const serialize = 'serialize' in opts ? ( + opts.serialize === false ? opts.serialize + : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) + ) : JSON.stringify + const remove = opts.remove + if (remove === true && serialize !== JSON.stringify) { + throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') + } + const censor = remove === true + ? undefined + : 'censor' in opts ? opts.censor : DEFAULT_CENSOR -exports.formatters = {}; + const isCensorFct = typeof censor === 'function' + const censorFctTakesPath = isCensorFct && censor.length > 1 -/** - * Previous log timestamp. - */ + if (paths.length === 0) return serialize || noop -var prevTime; + validate({ paths, serialize, censor }) -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; + const { wildcards, wcLen, secret } = parse({ paths, censor }) - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + const compileRestore = restorer({ secret, wcLen }) + const strict = 'strict' in opts ? opts.strict : true - return exports.colors[Math.abs(hash) % exports.colors.length]; + return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + })) } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // 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]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - // 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); +/***/ }), - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/***/ 54865: +/***/ ((module) => { - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); +"use strict"; - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +module.exports = { + groupRedact, + groupRestore, + nestedRedact, + nestedRestore +} - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); +function groupRestore ({ keys, values, target }) { + if (target == null) return + const length = keys.length + for (var i = 0; i < length; i++) { + const k = keys[i] + target[k] = values[i] } - - return debug; } -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; +function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return { keys: null, values: null, target: null, flat: true } + const keys = Object.keys(target) + const keysLength = keys.length + const pathLength = path.length + const pathWithKey = censorFctTakesPath ? [...path] : undefined + const values = new Array(keysLength) - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + values[i] = target[key] - 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) + '$')); + if (censorFctTakesPath) { + pathWithKey[pathLength] = key + target[key] = censor(target[key], pathWithKey) + } else if (isCensorFct) { + target[key] = censor(target[key]) } else { - exports.names.push(new RegExp('^' + namespaces + '$')); + target[key] = censor } } + return { keys, values, target, flat: true } } -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); +function nestedRestore (arr) { + const length = arr.length + for (var i = 0; i < length; i++) { + const { key, target, value } = arr[i] + target[key] = value + } } -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return + const keys = Object.keys(target) + const keysLength = keys.length + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + const { value, parent, exists } = + specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; + if (exists === true && parent !== null) { + store.push({ key: ns[ns.length - 1], target: parent, value }) } } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + return store +} + +function has (obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop) +} + +function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { + const afterPathLen = afterPath.length + const lastPathIndex = afterPathLen - 1 + const originalKey = k + var i = -1 + var n + var nv + var ov + var oov = null + var exists = true + ov = n = o[k] + if (typeof n !== 'object') return { value: null, parent: null, exists } + while (n != null && ++i < afterPathLen) { + k = afterPath[i] + oov = ov + if (!(k in n)) { + exists = false + break } + ov = n[k] + nv = (i !== lastPathIndex) + ? ov + : (isCensorFct + ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) + : censor) + n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv + n = n[k] + if (typeof n !== 'object') break } - return false; + return { value: ov, parent: oov, exists } } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function get (o, p) { + var i = -1 + var l = p.length + var n = o + while (n != null && ++i < l) { + n = n[p[i]] + } + return n } /***/ }), -/***/ 65612: +/***/ 96214: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ +"use strict"; -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(56401); -} else { - module.exports = __nccwpck_require__(4706); -} +const rx = __nccwpck_require__(9158) -/***/ }), +module.exports = parse -/***/ 4706: -/***/ ((module, exports, __nccwpck_require__) => { +function parse ({ paths }) { + const wildcards = [] + var wcLen = 0 + const secret = paths.reduce(function (o, strPath, ix) { + var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) + const leadingBracket = strPath[0] === '[' + path = path.map((p) => { + if (p[0] === '[') return p.substr(1, p.length - 2) + else return p + }) + const star = path.indexOf('*') + if (star > -1) { + const before = path.slice(0, star) + const beforeStr = before.join('.') + const after = path.slice(star + 1, path.length) + if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') + const nested = after.length > 0 + wcLen++ + wildcards.push({ + before, + beforeStr, + after, + nested + }) + } else { + o[strPath] = { + path: path, + val: undefined, + precensored: false, + circle: '', + escPath: JSON.stringify(strPath), + leadingBracket: leadingBracket + } + } + return o + }, {}) -/** - * Module dependencies. - */ + return { wildcards, wcLen, secret } +} -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +/***/ }), -exports = module.exports = __nccwpck_require__(60545); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +/***/ 17333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Colors. - */ +"use strict"; -exports.colors = [6, 2, 3, 4, 5, 1]; -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +const rx = __nccwpck_require__(9158) -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); +module.exports = redactor - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); +function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { + /* eslint-disable-next-line */ + const redact = Function('o', ` + if (typeof o !== 'object' || o == null) { + ${strictImpl(strict, serialize)} + } + const { censor, secret } = this + ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} + this.compileRestore() + ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} + ${resultTmpl(serialize)} + `).bind(state) - obj[prop] = val; - return obj; -}, {}); + if (serialize === false) { + redact.restore = (o) => state.restore(o) + } -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ + return redact +} -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +function redactTmpl (secret, isCensorFct, censorFctTakesPath) { + return Object.keys(secret).map((path) => { + const { escPath, leadingBracket, path: arrPath } = secret[path] + const skip = leadingBracket ? 1 : 0 + const delim = leadingBracket ? '' : '.' + const hops = [] + var match + while ((match = rx.exec(path)) !== null) { + const [ , ix ] = match + const { index, input } = match + if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) + } + var existence = hops.map((p) => `o${delim}${p}`).join(' && ') + if (existence.length === 0) existence += `o${delim}${path} != null` + else existence += ` && o${delim}${path} != null` -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} + const circularDetection = ` + switch (true) { + ${hops.reverse().map((p) => ` + case o${delim}${p} === censor: + secret[${escPath}].circle = ${JSON.stringify(p)} + break + `).join('\n')} + } + ` -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + const censorArgs = censorFctTakesPath + ? `val, ${JSON.stringify(arrPath)}` + : `val` -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + return ` + if (${existence}) { + const val = o${delim}${path} + if (val === censor) { + secret[${escPath}].precensored = true + } else { + secret[${escPath}].val = val + o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} + ${circularDetection} + } + } + ` + }).join('\n') +} -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); +function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { + return hasWildcards === true ? ` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) + } + } + ` : '' } -/** - * Map %o to `util.inspect()`, all on a single line. - */ +function resultTmpl (serialize) { + return serialize === false ? `return o` : ` + var s = this.serialize(o) + this.restore(o) + return s + ` +} -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; +function strictImpl (strict, serialize) { + return strict === true + ? `throw Error('fast-redact: primitives cannot be redacted')` + : serialize === false ? `return o` : `return this.serialize(o)` +} -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +/***/ }), -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ +/***/ 98806: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; +"use strict"; - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } -} +const { groupRestore, nestedRestore } = __nccwpck_require__(54865) -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ +module.exports = restorer -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); +function restorer ({ secret, wcLen }) { + return function compileRestore () { + if (this.restore) return + const paths = Object.keys(secret) + .filter((path) => secret[path].precensored === false) + const resetters = resetTmpl(secret, paths) + const hasWildcards = wcLen > 0 + const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } + /* eslint-disable-next-line */ + this.restore = Function( + 'o', + restoreTmpl(resetters, paths, hasWildcards) + ).bind(state) + } } /** - * Save `namespaces`. + * Mutates the original object to be censored by restoring its original values + * prior to censoring. * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} - -/** - * Load `namespaces`. + * @param {object} secret Compiled object describing which target fields should + * be censored and the field states. + * @param {string[]} paths The list of paths to censor as provided at + * initialization time. * - * @return {String} returns the previously persisted debug modes - * @api private + * @returns {string} String of JavaScript to be used by `Function()`. The + * string compiles to the function that does the work in the description. */ +function resetTmpl (secret, paths) { + return paths.map((path) => { + const { circle, escPath, leadingBracket } = secret[path] + const delim = leadingBracket ? '' : '.' + const reset = circle + ? `o.${circle} = secret[${escPath}].val` + : `o${delim}${path} = secret[${escPath}].val` + const clear = `secret[${escPath}].val = undefined` + return ` + if (secret[${escPath}].val !== undefined) { + try { ${reset} } catch (e) {} + ${clear} + } + ` + }).join('') +} -function load() { - return process.env.DEBUG; +function restoreTmpl (resetters, paths, hasWildcards) { + const dynamicReset = hasWildcards === true ? ` + const keys = Object.keys(secret) + const len = keys.length + for (var i = ${paths.length}; i < len; i++) { + const k = keys[i] + const o = secret[k] + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + ` : '' + + return ` + const secret = this.secret + ${resetters} + ${dynamicReset} + return o + ` } -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); +/***/ }), - // Note stream._type is used for test-module-load-list.js +/***/ 9158: +/***/ ((module) => { - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; +"use strict"; - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - case 'FILE': - var fs = __nccwpck_require__(35747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; +module.exports = /[^.[\]]+|\[((?:.)*?)\]/g - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(11631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); +/* +Regular expression explanation: - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; +Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) + opening square bracket ([) or closing square bracket (]) - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; +Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture + group (which will be capture group $1) that matches anything + within square brackets. Expansion is lazy so it will + stop matching as soon as the first closing bracket is met `]` + (rather than continuing to match until the final closing bracket). +*/ - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - // For supporting legacy API we put the FD here. - stream.fd = fd; +/***/ }), - stream._isStdio = true; +/***/ 41012: +/***/ ((module) => { - return stream; -} +"use strict"; -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ -function init (debug) { - debug.inspectOpts = {}; +module.exports = state - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } +function state (o) { + const { + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + } = o + const builder = [{ secret, censor, compileRestore }] + if (serialize !== false) builder.push({ serialize }) + if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) + return Object.assign(...builder) } -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ -exports.enable(load()); +/***/ }), +/***/ 74174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +"use strict"; -/***/ 80761: -/***/ ((module) => { -/** - * Helpers. - */ +const { createContext, runInContext } = __nccwpck_require__(92184) -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +module.exports = validator -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +function validator (opts = {}) { + const { + ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', + ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` + } = opts -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); + return function validate ({ paths }) { + paths.forEach((s) => { + if (typeof s !== 'string') { + throw Error(ERR_PATHS_MUST_BE_STRINGS()) + } + try { + if (/〇/.test(s)) throw Error() + const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) + const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') + if (/\n|\r|;/.test(expr)) throw Error() + if (/\/\*/.test(expr)) throw Error() + runInContext(` + (function () { + 'use strict' + o${expr} + if ([o${expr}].length !== 1) throw Error() + })() + `, createContext({ o: proxy, 〇: null }), { + codeGeneration: { strings: false, wasm: false } + }) + } catch (e) { + throw Error(ERR_INVALID_PATH(s)) + } + }) } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +} -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; +/***/ }), + +/***/ 17676: +/***/ ((module) => { + +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var arr = [] +var replacerStack = [] + +// Regular stringify +function stringify (obj, replacer, spacer) { + decirc(obj, '', [], undefined) + var res + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + return res +} +function decirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, stack, val) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, stack, val) + } + } + stack.pop() } } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 } - if (ms >= h) { - return Math.round(ms / h) + 'h'; + if (a > b) { + return 1 } - if (ms >= m) { - return Math.round(ms / m) + 'm'; + return 0 +} + +function deterministicStringify (obj, replacer, spacer) { + var tmp = deterministicDecirc(obj, '', [], undefined) || obj + var res + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) } - if (ms >= s) { - return Math.round(ms / s) + 's'; + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } } - return ms + 'ms'; + return res } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; +function deterministicDecirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + if (typeof val.toJSON === 'function') { + return + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, stack, val) + } + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, stack, val) + tmp[key] = val[key] + } + if (parent !== undefined) { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } + } + stack.pop() + } } -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; +// wraps replacer function to handle values we couldn't replace +// and mark them as [Circular] +function replaceGetterValues (replacer) { + replacer = replacer !== undefined ? replacer : function (k, v) { return v } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = '[Circular]' + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) } - return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }), -/***/ 35298: -/***/ ((module) => { +/***/ 34578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/* +Copyright (c) 2014 Petka Antonov -// You may be tempted to copy and paste this, -// but take a look at the commit history first, -// this is a moving target so relying on the module -// is the best way to make sure the optimization -// method is kept up to date and compatible with -// every Node version. - -function flatstr (s) { - s | 0 - return s -} - -module.exports = flatstr +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. -/***/ 68329: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); - -var util = __nccwpck_require__(31669), - fs = __nccwpck_require__(35747), - EventEmitter = __nccwpck_require__(28614).EventEmitter, - crypto = __nccwpck_require__(76417); - -function File(properties) { - EventEmitter.call(this); - - this.size = 0; - this.path = null; - this.name = null; - this.type = null; - this.hash = null; - this.lastModifiedDate = null; - - this._writeStream = null; - - for (var key in properties) { - this[key] = properties[key]; - } +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 Url() { + //For more efficient internal representation and laziness. + //The non-underscore versions of these properties are accessor functions + //defined on the prototype. + this._protocol = null; + this._href = ""; + this._port = -1; + this._query = null; - if(typeof this.hash === 'string') { - this.hash = crypto.createHash(properties.hash); - } else { + this.auth = null; + this.slashes = null; + this.host = null; + this.hostname = null; this.hash = null; - } + this.search = null; + this.pathname = null; + + this._prependSlash = false; } -module.exports = File; -util.inherits(File, EventEmitter); -File.prototype.open = function() { - this._writeStream = new fs.WriteStream(this.path); -}; +var querystring = __nccwpck_require__(71191); -File.prototype.toJSON = function() { - var json = { - size: this.size, - path: this.path, - name: this.name, - type: this.type, - mtime: this.lastModifiedDate, - length: this.length, - filename: this.filename, - mime: this.mime - }; - if (this.hash && this.hash != "") { - json.hash = this.hash; - } - return json; -}; +Url.queryString = querystring; -File.prototype.write = function(buffer, cb) { - var self = this; - if (self.hash) { - self.hash.update(buffer); - } +Url.prototype.parse = +function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { + if (typeof str !== "string") { + throw new TypeError("Parameter 'url' must be a string, not " + + typeof str); + } + var start = 0; + var end = str.length - 1; - if (this._writeStream.closed) { - return cb(); - } + //Trim leading and trailing ws + while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; + while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; - this._writeStream.write(buffer, function() { - self.lastModifiedDate = new Date(); - self.size += buffer.length; - self.emit('progress', self.size); - cb(); - }); -}; + start = this._parseProtocol(str, start, end); -File.prototype.end = function(cb) { - var self = this; - if (self.hash) { - self.hash = self.hash.digest('hex'); - } - this._writeStream.end(function() { - self.emit('end'); - cb(); - }); -}; + //Javascript doesn't have host + if (this._protocol !== "javascript") { + start = this._parseHost(str, start, end, hostDenotesSlash); + var proto = this._protocol; + if (!this.hostname && + (this.slashes || (proto && !slashProtocols[proto]))) { + this.hostname = this.host = ""; + } + } + if (start <= end) { + var ch = str.charCodeAt(start); -/***/ }), + if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { + this._parsePath(str, start, end, disableAutoEscapeChars); + } + else if (ch === 0x3F /*'?'*/) { + this._parseQuery(str, start, end, disableAutoEscapeChars); + } + else if (ch === 0x23 /*'#'*/) { + this._parseHash(str, start, end, disableAutoEscapeChars); + } + else if (this._protocol !== "javascript") { + this._parsePath(str, start, end, disableAutoEscapeChars); + } + else { //For javascript the pathname is just the rest of it + this.pathname = str.slice(start, end + 1 ); + } -/***/ 7973: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + } -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + if (!this.pathname && this.hostname && + this._slashProtocols[this._protocol]) { + this.pathname = "/"; + } -var crypto = __nccwpck_require__(76417); -var fs = __nccwpck_require__(35747); -var util = __nccwpck_require__(31669), - path = __nccwpck_require__(85622), - File = __nccwpck_require__(68329), - MultipartParser = __nccwpck_require__(31323).MultipartParser, - QuerystringParser = __nccwpck_require__(80825)/* .QuerystringParser */ .l, - OctetParser = __nccwpck_require__(48680)/* .OctetParser */ .h, - JSONParser = __nccwpck_require__(715)/* .JSONParser */ .c, - StringDecoder = __nccwpck_require__(24304).StringDecoder, - EventEmitter = __nccwpck_require__(28614).EventEmitter, - Stream = __nccwpck_require__(92413).Stream, - os = __nccwpck_require__(12087); + if (parseQueryString) { + var search = this.search; + if (search == null) { + search = this.search = ""; + } + if (search.charCodeAt(0) === 0x3F /*'?'*/) { + search = search.slice(1); + } + //This calls a setter function, there is no .query data property + this.query = Url.queryString.parse(search); + } +}; -function IncomingForm(opts) { - if (!(this instanceof IncomingForm)) return new IncomingForm(opts); - EventEmitter.call(this); +Url.prototype.resolve = function Url$resolve(relative) { + return this.resolveObject(Url.parse(relative, false, true)).format(); +}; - opts=opts||{}; +Url.prototype.format = function Url$format() { + var auth = this.auth || ""; - this.error = null; - this.ended = false; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ":"); + auth += "@"; + } - this.maxFields = opts.maxFields || 1000; - this.maxFieldsSize = opts.maxFieldsSize || 20 * 1024 * 1024; - this.maxFileSize = opts.maxFileSize || 200 * 1024 * 1024; - this.keepExtensions = opts.keepExtensions || false; - this.uploadDir = opts.uploadDir || (os.tmpdir && os.tmpdir()) || os.tmpDir(); - this.encoding = opts.encoding || 'utf-8'; - this.headers = null; - this.type = null; - this.hash = opts.hash || false; - this.multiples = opts.multiples || false; + var protocol = this.protocol || ""; + var pathname = this.pathname || ""; + var hash = this.hash || ""; + var search = this.search || ""; + var query = ""; + var hostname = this.hostname || ""; + var port = this.port || ""; + var host = false; + var scheme = ""; - this.bytesReceived = null; - this.bytesExpected = null; + //Cache the result of the getter function + var q = this.query; + if (q && typeof q === "object") { + query = Url.queryString.stringify(q); + } - this._parser = null; - this._flushing = 0; - this._fieldsSize = 0; - this._fileSize = 0; - this.openedFiles = []; + if (!search) { + search = query ? "?" + query : ""; + } - return this; -} -util.inherits(IncomingForm, EventEmitter); -exports.c = IncomingForm; + if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) + protocol += ":"; -IncomingForm.prototype.parse = function(req, cb) { - this.pause = function() { - try { - req.pause(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; + if (this.host) { + host = auth + this.host; } - return true; - }; - - this.resume = function() { - try { - req.resume(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; + else if (hostname) { + var ip6 = hostname.indexOf(":") > -1; + if (ip6) hostname = "[" + hostname + "]"; + host = auth + hostname + (port ? ":" + port : ""); } - return true; - }; - - // Setup callback first, so we don't miss anything from data events emitted - // immediately. - if (cb) { - var fields = {}, files = {}; - this - .on('field', function(name, value) { - fields[name] = value; - }) - .on('file', function(name, file) { - if (this.multiples) { - if (files[name]) { - if (!Array.isArray(files[name])) { - files[name] = [files[name]]; - } - files[name].push(file); - } else { - files[name] = file; - } - } else { - files[name] = file; - } - }) - .on('error', function(err) { - cb(err, fields, files); - }) - .on('end', function() { - cb(null, fields, files); - }); - } + var slashes = this.slashes || + ((!protocol || + slashProtocols[protocol]) && host !== false); - // Parse headers and setup the parser, ready to start listening for data. - this.writeHeaders(req.headers); - // Start listening for data. - var self = this; - req - .on('error', function(err) { - self._error(err); - }) - .on('aborted', function() { - self.emit('aborted'); - self._error(new Error('Request aborted')); - }) - .on('data', function(buffer) { - self.write(buffer); - }) - .on('end', function() { - if (self.error) { - return; - } + if (protocol) scheme = protocol + (slashes ? "//" : ""); + else if (slashes) scheme = "//"; - var err = self._parser.end(); - if (err) { - self._error(err); - } - }); + if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { + pathname = "/" + pathname; + } + if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) + search = "?" + search; + if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) + hash = "#" + hash; - return this; -}; + pathname = escapePathName(pathname); + search = escapeSearch(search); -IncomingForm.prototype.writeHeaders = function(headers) { - this.headers = headers; - this._parseContentLength(); - this._parseContentType(); + return scheme + (host === false ? "" : host) + pathname + search + hash; }; -IncomingForm.prototype.write = function(buffer) { - if (this.error) { - return; - } - if (!this._parser) { - this._error(new Error('uninitialized parser')); - return; - } - - this.bytesReceived += buffer.length; - this.emit('progress', this.bytesReceived, this.bytesExpected); - - var bytesParsed = this._parser.write(buffer); - if (bytesParsed !== buffer.length) { - this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); - } - - return bytesParsed; -}; +Url.prototype.resolveObject = function Url$resolveObject(relative) { + if (typeof relative === "string") + relative = Url.parse(relative, false, true); -IncomingForm.prototype.pause = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; + var result = this._clone(); -IncomingForm.prototype.resume = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; -IncomingForm.prototype.onPart = function(part) { - // this method can be overwritten by the user - this.handlePart(part); -}; + // if the relative url is empty, then there"s nothing left to do here. + if (!relative.href) { + result._href = ""; + return result; + } -IncomingForm.prototype.handlePart = function(part) { - var self = this; + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative._protocol) { + relative._copyPropsTo(result, true); - // This MUST check exactly for undefined. You can not change it to !part.filename. - if (part.filename === undefined) { - var value = '' - , decoder = new StringDecoder(this.encoding); + if (slashProtocols[result._protocol] && + result.hostname && !result.pathname) { + result.pathname = "/"; + } + result._href = ""; + return result; + } - part.on('data', function(buffer) { - self._fieldsSize += buffer.length; - if (self._fieldsSize > self.maxFieldsSize) { - self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); - return; - } - value += decoder.write(buffer); - }); + if (relative._protocol && relative._protocol !== result._protocol) { + // if it"s a known url protocol, then changing + // the protocol does weird things + // first, if it"s not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that"s known to be hostless. + // anything else is assumed to be absolute. + if (!slashProtocols[relative._protocol]) { + relative._copyPropsTo(result, false); + result._href = ""; + return result; + } - part.on('end', function() { - self.emit('field', part.name, value); - }); - return; - } + result._protocol = relative._protocol; + if (!relative.host && relative._protocol !== "javascript") { + var relPath = (relative.pathname || "").split("/"); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ""; + if (!relative.hostname) relative.hostname = ""; + if (relPath[0] !== "") relPath.unshift(""); + if (relPath.length < 2) relPath.unshift(""); + result.pathname = relPath.join("/"); + } else { + result.pathname = relative.pathname; + } - this._flushing++; + result.search = relative.search; + result.host = relative.host || ""; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result._port = relative._port; + result.slashes = result.slashes || relative.slashes; + result._href = ""; + return result; + } - var file = new File({ - path: this._uploadPath(part.filename), - name: part.filename, - type: part.mime, - hash: self.hash - }); + var isSourceAbs = + (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/); + var isRelAbs = ( + relative.host || + (relative.pathname && + relative.pathname.charCodeAt(0) === 0x2F /*'/'*/) + ); + var mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)); - this.emit('fileBegin', part.name, file); + var removeAllDots = mustEndAbs; - file.open(); - this.openedFiles.push(file); + var srcPath = result.pathname && result.pathname.split("/") || []; + var relPath = relative.pathname && relative.pathname.split("/") || []; + var psychotic = result._protocol && !slashProtocols[result._protocol]; - part.on('data', function(buffer) { - self._fileSize += buffer.length; - if (self._fileSize > self.maxFileSize) { - self._error(new Error('maxFileSize exceeded, received '+self._fileSize+' bytes of file data')); - return; - } - if (buffer.length == 0) { - return; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ""; + result._port = -1; + if (result.host) { + if (srcPath[0] === "") srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ""; + if (relative._protocol) { + relative.hostname = ""; + relative._port = -1; + if (relative.host) { + if (relPath[0] === "") relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = ""; + } + mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); } - self.pause(); - file.write(buffer, function() { - self.resume(); - }); - }); - - part.on('end', function() { - file.end(function() { - self._flushing--; - self.emit('file', part.name, file); - self._maybeEnd(); - }); - }); -}; -function dummyParser(self) { - return { - end: function () { - self.ended = true; - self._maybeEnd(); - return null; + if (isRelAbs) { + // it"s absolute. + result.host = relative.host ? + relative.host : result.host; + result.hostname = relative.hostname ? + relative.hostname : result.hostname; + result.search = relative.search; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it"s relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + } else if (relative.search) { + // just pull out the search. + // like href="?foo". + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especialy happens in cases like + //url.resolveObject("mailto:local1@domain1", "local2@domain2") + var authInHost = result.host && result.host.indexOf("@") > 0 ? + result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result._href = ""; + return result; } - }; -} - -IncomingForm.prototype._parseContentType = function() { - if (this.bytesExpected === 0) { - this._parser = dummyParser(this); - return; - } - if (!this.headers['content-type']) { - this._error(new Error('bad content-type header, no content-type')); - return; - } + if (!srcPath.length) { + // no path at all. easy. + // we"ve already handled the other stuff above. + result.pathname = null; + result._href = ""; + return result; + } - if (this.headers['content-type'].match(/octet-stream/i)) { - this._initOctetStream(); - return; - } + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host) && (last === "." || last === "..") || + last === ""); - if (this.headers['content-type'].match(/urlencoded/i)) { - this._initUrlencoded(); - return; - } + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === ".") { + srcPath.splice(i, 1); + } else if (last === "..") { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } - if (this.headers['content-type'].match(/multipart/i)) { - var m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i); - if (m) { - this._initMultipart(m[1] || m[2]); - } else { - this._error(new Error('bad content-type header, no multipart boundary')); + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift(".."); + } } - return; - } - if (this.headers['content-type'].match(/json/i)) { - this._initJSONencoded(); - return; - } + if (mustEndAbs && srcPath[0] !== "" && + (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { + srcPath.unshift(""); + } - this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); -}; + if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { + srcPath.push(""); + } -IncomingForm.prototype._error = function(err) { - if (this.error || this.ended) { - return; - } + var isAbsolute = srcPath[0] === "" || + (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); - this.error = err; - this.emit('error', err); + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? "" : + srcPath.length ? srcPath.shift() : ""; + //occationaly the auth can get stuck only in host + //this especialy happens in cases like + //url.resolveObject("mailto:local1@domain1", "local2@domain2") + var authInHost = result.host && result.host.indexOf("@") > 0 ? + result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } - if (Array.isArray(this.openedFiles)) { - this.openedFiles.forEach(function(file) { - file._writeStream.destroy(); - setTimeout(fs.unlink, 0, file.path, function(error) { }); - }); - } -}; + mustEndAbs = mustEndAbs || (result.host && srcPath.length); -IncomingForm.prototype._parseContentLength = function() { - this.bytesReceived = 0; - if (this.headers['content-length']) { - this.bytesExpected = parseInt(this.headers['content-length'], 10); - } else if (this.headers['transfer-encoding'] === undefined) { - this.bytesExpected = 0; - } + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } - if (this.bytesExpected !== null) { - this.emit('progress', this.bytesReceived, this.bytesExpected); - } + result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result._href = ""; + return result; }; -IncomingForm.prototype._newParser = function() { - return new MultipartParser(); +var punycode = __nccwpck_require__(94213); +Url.prototype._hostIdna = function Url$_hostIdna(hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + return punycode.toASCII(hostname); }; -IncomingForm.prototype._initMultipart = function(boundary) { - this.type = 'multipart'; +var escapePathName = Url.prototype._escapePathName = +function Url$_escapePathName(pathname) { + if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { + return pathname; + } + //Avoid closure creation to keep this inlinable + return _escapePath(pathname); +}; - var parser = new MultipartParser(), - self = this, - headerField, - headerValue, - part; +var escapeSearch = Url.prototype._escapeSearch = +function Url$_escapeSearch(search) { + if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search; + //Avoid closure creation to keep this inlinable + return _escapeSearch(search); +}; - parser.initWithBoundary(boundary); +Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { + var doLowerCase = false; + var protocolCharacters = this._protocolCharacters; - parser.onPartBegin = function() { - part = new Stream(); - part.readable = true; - part.headers = {}; - part.name = null; - part.filename = null; - part.mime = null; + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); - part.transferEncoding = 'binary'; - part.transferBuffer = ''; + if (ch === 0x3A /*':'*/) { + var protocol = str.slice(start, i); + if (doLowerCase) protocol = protocol.toLowerCase(); + this._protocol = protocol; + return i + 1; + } + else if (protocolCharacters[ch] === 1) { + if (ch < 0x61 /*'a'*/) + doLowerCase = true; + } + else { + return start; + } - headerField = ''; - headerValue = ''; - }; + } + return start; +}; - parser.onHeaderField = function(b, start, end) { - headerField += b.toString(self.encoding, start, end); - }; +Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) { + var auth = str.slice(start, end + 1); + if (decode) { + auth = decodeURIComponent(auth); + } + this.auth = auth; +}; - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString(self.encoding, start, end); - }; +Url.prototype._parsePort = function Url$_parsePort(str, start, end) { + //Internal format is integer for more efficient parsing + //and for efficient trimming of leading zeros + var port = 0; + //Distinguish between :0 and : (no port number at all) + var hadChars = false; + var validPort = true; - parser.onHeaderEnd = function() { - headerField = headerField.toLowerCase(); - part.headers[headerField] = headerValue; + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); - // matches either a quoted-string or a token (RFC 2616 section 19.5.1) - var m = headerValue.match(/\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i); - if (headerField == 'content-disposition') { - if (m) { - part.name = m[2] || m[3] || ''; - } + if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) { + port = (10 * port) + (ch - 0x30 /*'0'*/); + hadChars = true; + } + else { + validPort = false; + if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) { + validPort = true; + } + break; + } - part.filename = self._fileName(headerValue); - } else if (headerField == 'content-type') { - part.mime = headerValue; - } else if (headerField == 'content-transfer-encoding') { - part.transferEncoding = headerValue.toLowerCase(); + } + if ((port === 0 && !hadChars) || !validPort) { + if (!validPort) { + this._port = -2; + } + return 0; } - headerField = ''; - headerValue = ''; - }; + this._port = port; + return i - start; +}; - parser.onHeadersEnd = function() { - switch(part.transferEncoding){ - case 'binary': - case '7bit': - case '8bit': - parser.onPartData = function(b, start, end) { - part.emit('data', b.slice(start, end)); - }; +Url.prototype._parseHost = +function Url$_parseHost(str, start, end, slashesDenoteHost) { + var hostEndingCharacters = this._hostEndingCharacters; + var first = str.charCodeAt(start); + var second = str.charCodeAt(start + 1); + if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) && + (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) { + this.slashes = true; - parser.onPartEnd = function() { - part.emit('end'); - }; - break; + //The string starts with // + if (start === 0) { + //The string is just "//" + if (end < 2) return start; + //If slashes do not denote host and there is no auth, + //there is no host when the string starts with // + var hasAuth = + containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters); + if (!hasAuth && !slashesDenoteHost) { + this.slashes = null; + return start; + } + } + //There is a host that starts after the // + start += 2; + } + //If there is no slashes, there is no hostname if + //1. there was no protocol at all + else if (!this._protocol || + //2. there was a protocol that requires slashes + //e.g. in 'http:asd' 'asd' is not a hostname + slashProtocols[this._protocol] + ) { + return start; + } - case 'base64': - parser.onPartData = function(b, start, end) { - part.transferBuffer += b.slice(start, end).toString('ascii'); + var doLowerCase = false; + var idna = false; + var hostNameStart = start; + var hostNameEnd = end; + var lastCh = -1; + var portLength = 0; + var charsAfterDot = 0; + var authNeedsDecoding = false; - /* - four bytes (chars) in base64 converts to three bytes in binary - encoding. So we should always work with a number of bytes that - can be divided by 4, it will result in a number of buytes that - can be divided vy 3. - */ - var offset = parseInt(part.transferBuffer.length / 4, 10) * 4; - part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64')); - part.transferBuffer = part.transferBuffer.substring(offset); - }; + var j = -1; - parser.onPartEnd = function() { - part.emit('data', new Buffer(part.transferBuffer, 'base64')); - part.emit('end'); - }; - break; + //Find the last occurrence of an @-sign until hostending character is met + //also mark if decoding is needed for the auth portion + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); - default: - return self._error(new Error('unknown transfer-encoding')); + if (ch === 0x40 /*'@'*/) { + j = i; + } + //This check is very, very cheap. Unneeded decodeURIComponent is very + //very expensive + else if (ch === 0x25 /*'%'*/) { + authNeedsDecoding = true; + } + else if (hostEndingCharacters[ch] === 1) { + break; + } } - self.onPart(part); - }; - - - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; + //@-sign was found at index j, everything to the left from it + //is auth part + if (j > -1) { + this._parseAuth(str, start, j - 1, authNeedsDecoding); + //hostname starts after the last @-sign + start = hostNameStart = j + 1; + } - this._parser = parser; -}; + //Host name is starting with a [ + if (str.charCodeAt(start) === 0x5B /*'['*/) { + for (var i = start + 1; i <= end; ++i) { + var ch = str.charCodeAt(i); -IncomingForm.prototype._fileName = function(headerValue) { - // matches either a quoted-string or a token (RFC 2616 section 19.5.1) - var m = headerValue.match(/\bfilename=("(.*?)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))($|;\s)/i); - if (!m) return; + //Assume valid IP6 is between the brackets + if (ch === 0x5D /*']'*/) { + if (str.charCodeAt(i + 1) === 0x3A /*':'*/) { + portLength = this._parsePort(str, i + 2, end) + 1; + } + var hostname = str.slice(start + 1, i).toLowerCase(); + this.hostname = hostname; + this.host = this._port > 0 ? + "[" + hostname + "]:" + this._port : + "[" + hostname + "]"; + this.pathname = "/"; + return i + portLength + 1; + } + } + //Empty hostname, [ starts a path + return start; + } - var match = m[2] || m[3] || ''; - var filename = match.substr(match.lastIndexOf('\\') + 1); - filename = filename.replace(/%22/g, '"'); - filename = filename.replace(/&#([\d]{4});/g, function(m, code) { - return String.fromCharCode(code); - }); - return filename; -}; + for (var i = start; i <= end; ++i) { + if (charsAfterDot > 62) { + this.hostname = this.host = str.slice(start, i); + return i; + } + var ch = str.charCodeAt(i); -IncomingForm.prototype._initUrlencoded = function() { - this.type = 'urlencoded'; + if (ch === 0x3A /*':'*/) { + portLength = this._parsePort(str, i + 1, end) + 1; + hostNameEnd = i - 1; + break; + } + else if (ch < 0x61 /*'a'*/) { + if (ch === 0x2E /*'.'*/) { + //Node.js ignores this error + /* + if (lastCh === DOT || lastCh === -1) { + this.hostname = this.host = ""; + return start; + } + */ + charsAfterDot = -1; + } + else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { + doLowerCase = true; + } + //Valid characters other than ASCII letters -, _, +, 0-9 + else if (!(ch === 0x2D /*'-'*/ || + ch === 0x5F /*'_'*/ || + ch === 0x2B /*'+'*/ || + (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/)) + ) { + if (hostEndingCharacters[ch] === 0 && + this._noPrependSlashHostEnders[ch] === 0) { + this._prependSlash = true; + } + hostNameEnd = i - 1; + break; + } + } + else if (ch >= 0x7B /*'{'*/) { + if (ch <= 0x7E /*'~'*/) { + if (this._noPrependSlashHostEnders[ch] === 0) { + this._prependSlash = true; + } + hostNameEnd = i - 1; + break; + } + idna = true; + } + lastCh = ch; + charsAfterDot++; + } - var parser = new QuerystringParser(this.maxFields) - , self = this; + //Node.js ignores this error + /* + if (lastCh === DOT) { + hostNameEnd--; + } + */ - parser.onField = function(key, val) { - self.emit('field', key, val); - }; + if (hostNameEnd + 1 !== start && + hostNameEnd - hostNameStart <= 256) { + var hostname = str.slice(hostNameStart, hostNameEnd + 1); + if (doLowerCase) hostname = hostname.toLowerCase(); + if (idna) hostname = this._hostIdna(hostname); + this.hostname = hostname; + this.host = this._port > 0 ? hostname + ":" + this._port : hostname; + } - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; + return hostNameEnd + 1 + portLength; - this._parser = parser; }; -IncomingForm.prototype._initOctetStream = function() { - this.type = 'octet-stream'; - var filename = this.headers['x-file-name']; - var mime = this.headers['content-type']; - - var file = new File({ - path: this._uploadPath(filename), - name: filename, - type: mime - }); +Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { + if (!noProtocol) { + input._protocol = this._protocol; + } + input._href = this._href; + input._port = this._port; + input._prependSlash = this._prependSlash; + input.auth = this.auth; + input.slashes = this.slashes; + input.host = this.host; + input.hostname = this.hostname; + input.hash = this.hash; + input.search = this.search; + input.pathname = this.pathname; +}; - this.emit('fileBegin', filename, file); - file.open(); - this.openedFiles.push(file); - this._flushing++; +Url.prototype._clone = function Url$_clone() { + var ret = new Url(); + ret._protocol = this._protocol; + ret._href = this._href; + ret._port = this._port; + ret._prependSlash = this._prependSlash; + ret.auth = this.auth; + ret.slashes = this.slashes; + ret.host = this.host; + ret.hostname = this.hostname; + ret.hash = this.hash; + ret.search = this.search; + ret.pathname = this.pathname; + return ret; +}; - var self = this; +Url.prototype._getComponentEscaped = +function Url$_getComponentEscaped(str, start, end, isAfterQuery) { + var cur = start; + var i = start; + var ret = ""; + var autoEscapeMap = isAfterQuery ? + this._afterQueryAutoEscapeMap : this._autoEscapeMap; + for (; i <= end; ++i) { + var ch = str.charCodeAt(i); + var escaped = autoEscapeMap[ch]; - self._parser = new OctetParser(); + if (escaped !== "" && escaped !== undefined) { + if (cur < i) ret += str.slice(cur, i); + ret += escaped; + cur = i + 1; + } + } + if (cur < i + 1) ret += str.slice(cur, i); + return ret; +}; - //Keep track of writes that haven't finished so we don't emit the file before it's done being written - var outstandingWrites = 0; +Url.prototype._parsePath = +function Url$_parsePath(str, start, end, disableAutoEscapeChars) { + var pathStart = start; + var pathEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; + var prePath = this._port === -2 ? "/:" : ""; - self._parser.on('data', function(buffer){ - self.pause(); - outstandingWrites++; + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + pathEnd = i - 1; + break; + } + else if (ch === 0x3F /*'?'*/) { + this._parseQuery(str, i, end, disableAutoEscapeChars); + pathEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; + } + } - file.write(buffer, function() { - outstandingWrites--; - self.resume(); + if (pathStart > pathEnd) { + this.pathname = prePath === "" ? "/" : prePath; + return; + } - if(self.ended){ - self._parser.emit('doneWritingFile'); - } - }); - }); + var path; + if (escape) { + path = this._getComponentEscaped(str, pathStart, pathEnd, false); + } + else { + path = str.slice(pathStart, pathEnd + 1); + } + this.pathname = prePath === "" + ? (this._prependSlash ? "/" + path : path) + : prePath + path; +}; - self._parser.on('end', function(){ - self._flushing--; - self.ended = true; +Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { + var queryStart = start; + var queryEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; - var done = function(){ - file.end(function() { - self.emit('file', 'file', file); - self._maybeEnd(); - }); - }; + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); - if(outstandingWrites === 0){ - done(); - } else { - self._parser.once('doneWritingFile', done); + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + queryEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; + } } - }); + + if (queryStart > queryEnd) { + this.search = ""; + return; + } + + var query; + if (escape) { + query = this._getComponentEscaped(str, queryStart, queryEnd, true); + } + else { + query = str.slice(queryStart, queryEnd + 1); + } + this.search = query; }; -IncomingForm.prototype._initJSONencoded = function() { - this.type = 'json'; +Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { + if (start > end) { + this.hash = ""; + return; + } - var parser = new JSONParser(this) - , self = this; + this.hash = disableAutoEscapeChars ? + str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); +}; - parser.onField = function(key, val) { - self.emit('field', key, val); - }; +Object.defineProperty(Url.prototype, "port", { + get: function() { + if (this._port >= 0) { + return ("" + this._port); + } + return null; + }, + set: function(v) { + if (v == null) { + this._port = -1; + } + else { + this._port = parseInt(v, 10); + } + } +}); - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; +Object.defineProperty(Url.prototype, "query", { + get: function() { + var query = this._query; + if (query != null) { + return query; + } + var search = this.search; - this._parser = parser; -}; + if (search) { + if (search.charCodeAt(0) === 0x3F /*'?'*/) { + search = search.slice(1); + } + if (search !== "") { + this._query = search; + return search; + } + } + return search; + }, + set: function(v) { + this._query = v; + } +}); -IncomingForm.prototype._uploadPath = function(filename) { - var buf = crypto.randomBytes(16); - var name = 'upload_' + buf.toString('hex'); +Object.defineProperty(Url.prototype, "path", { + get: function() { + var p = this.pathname || ""; + var s = this.search || ""; + if (p || s) { + return p + s; + } + return (p == null && s) ? ("/" + s) : null; + }, + set: function() {} +}); - if (this.keepExtensions) { - var ext = path.extname(filename); - ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); +Object.defineProperty(Url.prototype, "protocol", { + get: function() { + var proto = this._protocol; + return proto ? proto + ":" : proto; + }, + set: function(v) { + if (typeof v === "string") { + var end = v.length - 1; + if (v.charCodeAt(end) === 0x3A /*':'*/) { + this._protocol = v.slice(0, end); + } + else { + this._protocol = v; + } + } + else if (v == null) { + this._protocol = null; + } + } +}); - name += ext; - } +Object.defineProperty(Url.prototype, "href", { + get: function() { + var href = this._href; + if (!href) { + href = this._href = this.format(); + } + return href; + }, + set: function(v) { + this._href = v; + } +}); - return path.join(this.uploadDir, name); +Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { + if (str instanceof Url) return str; + var ret = new Url(); + ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars); + return ret; }; -IncomingForm.prototype._maybeEnd = function() { - if (!this.ended || this._flushing || this.error) { - return; - } - - this.emit('end'); +Url.format = function Url$Format(obj) { + if (typeof obj === "string") { + obj = Url.parse(obj); + } + if (!(obj instanceof Url)) { + return Url.prototype.format.call(obj); + } + return obj.format(); }; +Url.resolve = function Url$Resolve(source, relative) { + return Url.parse(source, false, true).resolve(relative); +}; -/***/ }), +Url.resolveObject = function Url$ResolveObject(source, relative) { + if (!source) return relative; + return Url.parse(source, false, true).resolveObject(relative); +}; -/***/ 95265: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function _escapePath(pathname) { + return pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); +} -var IncomingForm = __nccwpck_require__(7973)/* .IncomingForm */ .c; -IncomingForm.IncomingForm = IncomingForm; -module.exports = IncomingForm; +function _escapeSearch(search) { + return search.replace(/#/g, function(match) { + return encodeURIComponent(match); + }); +} +//Search `char1` (integer code for a character) in `string` +//starting from `fromIndex` and ending at `string.length - 1` +//or when a stop character is found +function containsCharacter(string, char1, fromIndex, stopCharacterTable) { + var len = string.length; + for (var i = fromIndex; i < len; ++i) { + var ch = string.charCodeAt(i); -/***/ }), + if (ch === char1) { + return true; + } + else if (stopCharacterTable[ch] === 1) { + return false; + } + } + return false; +} -/***/ 715: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +//See if `char1` or `char2` (integer codes for characters) +//is contained in `string` +function containsCharacter2(string, char1, char2) { + for (var i = 0, len = string.length; i < len; ++i) { + var ch = string.charCodeAt(i); + if (ch === char1 || ch === char2) return true; + } + return false; +} -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); +//Makes an array of 128 uint8's which represent boolean values. +//Spec is an array of ascii code points or ascii code point ranges +//ranges are expressed as [start, end] -var Buffer = __nccwpck_require__(64293).Buffer; +//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and +//0x7A (lowercaseletter 'z') as `true`: +// +//var a = makeAsciiTable([[0x30, 0x39], 0x7A]); +//a[0x30]; //1 +//a[0x15]; //0 +//a[0x35]; //1 +function makeAsciiTable(spec) { + var ret = new Uint8Array(128); + spec.forEach(function(item){ + if (typeof item === "number") { + ret[item] = 1; + } + else { + var start = item[0]; + var end = item[1]; + for (var j = start; j <= end; ++j) { + ret[j] = 1; + } + } + }); -function JSONParser(parent) { - this.parent = parent; - this.chunks = []; - this.bytesWritten = 0; + return ret; } -exports.c = JSONParser; -JSONParser.prototype.write = function(buffer) { - this.bytesWritten += buffer.length; - this.chunks.push(buffer); - return buffer.length; -}; -JSONParser.prototype.end = function() { - try { - var fields = JSON.parse(Buffer.concat(this.chunks)); - for (var field in fields) { - this.onField(field, fields[field]); +var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", + "\t", "{", "}", "|", "\\", "^", "`", "'"]; + +var autoEscapeMap = new Array(128); + + + +for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { + autoEscapeMap[i] = ""; +} + +for (var i = 0, len = autoEscape.length; i < len; ++i) { + var c = autoEscape[i]; + var esc = encodeURIComponent(c); + if (esc === c) { + esc = escape(c); } - } catch (e) { - this.parent.emit('error', e); - } - this.data = null; + autoEscapeMap[c.charCodeAt(0)] = esc; +} +var afterQueryAutoEscapeMap = autoEscapeMap.slice(); +autoEscapeMap[0x5C /*'\'*/] = "/"; - this.onEnd(); +var slashProtocols = Url.prototype._slashProtocols = { + http: true, + https: true, + gopher: true, + file: true, + ftp: true, + + "http:": true, + "https:": true, + "gopher:": true, + "file:": true, + "ftp:": true }; +//Optimize back from normalized object caused by non-identifier keys +function f(){} +f.prototype = slashProtocols; -/***/ }), +Url.prototype._protocolCharacters = makeAsciiTable([ + [0x61 /*'a'*/, 0x7A /*'z'*/], + [0x41 /*'A'*/, 0x5A /*'Z'*/], + 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ +]); -/***/ 31323: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Url.prototype._hostEndingCharacters = makeAsciiTable([ + 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ +]); -var Buffer = __nccwpck_require__(64293).Buffer, - s = 0, - S = - { PARSER_UNINITIALIZED: s++, - START: s++, - START_BOUNDARY: s++, - HEADER_FIELD_START: s++, - HEADER_FIELD: s++, - HEADER_VALUE_START: s++, - HEADER_VALUE: s++, - HEADER_VALUE_ALMOST_DONE: s++, - HEADERS_ALMOST_DONE: s++, - PART_DATA_START: s++, - PART_DATA: s++, - PART_END: s++, - END: s++ - }, +Url.prototype._autoEscapeCharacters = makeAsciiTable( + autoEscape.map(function(v) { + return v.charCodeAt(0); + }) +); - f = 1, - F = - { PART_BOUNDARY: f, - LAST_BOUNDARY: f *= 2 - }, +//If these characters end a host name, the path will not be prepended a / +Url.prototype._noPrependSlashHostEnders = makeAsciiTable( + [ + "<", ">", "'", "`", " ", "\r", + "\n", "\t", "{", "}", "|", + "^", "`", "\"", "%", ";" + ].map(function(v) { + return v.charCodeAt(0); + }) +); - LF = 10, - CR = 13, - SPACE = 32, - HYPHEN = 45, - COLON = 58, - A = 97, - Z = 122, +Url.prototype._autoEscapeMap = autoEscapeMap; +Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; - lower = function(c) { - return c | 0x20; +module.exports = Url; + +Url.replace = function Url$Replace() { + require.cache.url = { + exports: Url }; +}; -for (s in S) { - exports[s] = S[s]; -} -function MultipartParser() { - this.boundary = null; - this.boundaryChars = null; - this.lookbehind = null; - this.state = S.PARSER_UNINITIALIZED; +/***/ }), - this.index = null; - this.flags = 0; -} -exports.MultipartParser = MultipartParser; +/***/ 30810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -MultipartParser.stateToString = function(stateNumber) { - for (var state in S) { - var number = S[state]; - if (number === stateNumber) return state; - } -}; +"use strict"; +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ -MultipartParser.prototype.initWithBoundary = function(str) { - this.boundary = new Buffer(str.length+4); - this.boundary.write('\r\n--', 0); - this.boundary.write(str, 4); - this.lookbehind = new Buffer(this.boundary.length+8); - this.state = S.START; - this.boundaryChars = {}; - for (var i = 0; i < this.boundary.length; i++) { - this.boundaryChars[this.boundary[i]] = true; - } -}; -MultipartParser.prototype.write = function(buffer) { - var self = this, - i = 0, - len = buffer.length, - prevIndex = this.index, - index = this.index, - state = this.state, - flags = this.flags, - lookbehind = this.lookbehind, - boundary = this.boundary, - boundaryChars = this.boundaryChars, - boundaryLength = this.boundary.length, - boundaryEnd = boundaryLength - 1, - bufferLength = buffer.length, - c, - cl, +/** + * Module dependencies. + * @private + */ - mark = function(name) { - self[name+'Mark'] = i; - }, - clear = function(name) { - delete self[name+'Mark']; - }, - callback = function(name, buffer, start, end) { - if (start !== undefined && start === end) { - return; - } +var debug = __nccwpck_require__(65612)('finalhandler') +var encodeUrl = __nccwpck_require__(16592) +var escapeHtml = __nccwpck_require__(94070) +var onFinished = __nccwpck_require__(92098) +var parseUrl = __nccwpck_require__(89808) +var statuses = __nccwpck_require__(57415) +var unpipe = __nccwpck_require__(3124) - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](buffer, start, end); - } - }, - dataCallback = function(name, clear) { - var markSymbol = name+'Mark'; - if (!(markSymbol in self)) { - return; - } +/** + * Module variables. + * @private + */ - if (!clear) { - callback(name, buffer, self[markSymbol], buffer.length); - self[markSymbol] = 0; - } else { - callback(name, buffer, self[markSymbol], i); - delete self[markSymbol]; - } - }; +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g - for (i = 0; i < len; i++) { - c = buffer[i]; - switch (state) { - case S.PARSER_UNINITIALIZED: - return i; - case S.START: - index = 0; - state = S.START_BOUNDARY; - case S.START_BOUNDARY: - if (index == boundary.length - 2) { - if (c == HYPHEN) { - flags |= F.LAST_BOUNDARY; - } else if (c != CR) { - return i; - } - index++; - break; - } else if (index - 1 == boundary.length - 2) { - if (flags & F.LAST_BOUNDARY && c == HYPHEN){ - callback('end'); - state = S.END; - flags = 0; - } else if (!(flags & F.LAST_BOUNDARY) && c == LF) { - index = 0; - callback('partBegin'); - state = S.HEADER_FIELD_START; - } else { - return i; - } - break; - } +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished - if (c != boundary[index+2]) { - index = -2; - } - if (c == boundary[index+2]) { - index++; - } - break; - case S.HEADER_FIELD_START: - state = S.HEADER_FIELD; - mark('headerField'); - index = 0; - case S.HEADER_FIELD: - if (c == CR) { - clear('headerField'); - state = S.HEADERS_ALMOST_DONE; - break; - } +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ - index++; - if (c == HYPHEN) { - break; - } +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') - if (c == COLON) { - if (index == 1) { - // empty header field - return i; - } - dataCallback('headerField', true); - state = S.HEADER_VALUE_START; - break; - } + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} - cl = lower(c); - if (cl < A || cl > Z) { - return i; - } - break; - case S.HEADER_VALUE_START: - if (c == SPACE) { - break; - } +/** + * Module exports. + * @public + */ - mark('headerValue'); - state = S.HEADER_VALUE; - case S.HEADER_VALUE: - if (c == CR) { - dataCallback('headerValue', true); - callback('headerEnd'); - state = S.HEADER_VALUE_ALMOST_DONE; - } - break; - case S.HEADER_VALUE_ALMOST_DONE: - if (c != LF) { - return i; - } - state = S.HEADER_FIELD_START; - break; - case S.HEADERS_ALMOST_DONE: - if (c != LF) { - return i; - } +module.exports = finalhandler - callback('headersEnd'); - state = S.PART_DATA_START; - break; - case S.PART_DATA_START: - state = S.PART_DATA; - mark('partData'); - case S.PART_DATA: - prevIndex = index; +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ - if (index === 0) { - // boyer-moore derrived algorithm to safely skip non-boundary data - i += boundaryEnd; - while (i < bufferLength && !(buffer[i] in boundaryChars)) { - i += boundaryLength; - } - i -= boundaryEnd; - c = buffer[i]; - } +function finalhandler (req, res, options) { + var opts = options || {} - if (index < boundary.length) { - if (boundary[index] == c) { - if (index === 0) { - dataCallback('partData', true); - } - index++; - } else { - index = 0; - } - } else if (index == boundary.length) { - index++; - if (c == CR) { - // CR = part boundary - flags |= F.PART_BOUNDARY; - } else if (c == HYPHEN) { - // HYPHEN = end boundary - flags |= F.LAST_BOUNDARY; - } else { - index = 0; - } - } else if (index - 1 == boundary.length) { - if (flags & F.PART_BOUNDARY) { - index = 0; - if (c == LF) { - // unset the PART_BOUNDARY flag - flags &= ~F.PART_BOUNDARY; - callback('partEnd'); - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - } else if (flags & F.LAST_BOUNDARY) { - if (c == HYPHEN) { - callback('partEnd'); - callback('end'); - state = S.END; - flags = 0; - } else { - index = 0; - } - } else { - index = 0; - } - } + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' - if (index > 0) { - // when matching a possible boundary, keep a lookbehind reference - // in case it turns out to be a false lead - lookbehind[index-1] = c; - } else if (prevIndex > 0) { - // if our boundary turned out to be rubbish, the captured lookbehind - // belongs to partData - callback('partData', lookbehind, 0, prevIndex); - prevIndex = 0; - mark('partData'); + // get error callback + var onerror = opts.onerror - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } + return function (err) { + var headers + var msg + var status - break; - case S.END: - break; - default: - return i; + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return } - } - - dataCallback('headerField'); - dataCallback('headerValue'); - dataCallback('partData'); - this.index = index; - this.state = state; - this.flags = flags; + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) - return len; -}; + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } -MultipartParser.prototype.end = function() { - var callback = function(self, name) { - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](); + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) } - }; - if ((this.state == S.HEADER_FIELD_START && this.index === 0) || - (this.state == S.PART_DATA && this.index == this.boundary.length)) { - callback(this, 'partEnd'); - callback(this, 'end'); - } else if (this.state != S.END) { - return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); - } -}; - -MultipartParser.prototype.explain = function() { - return 'state = ' + MultipartParser.stateToString(this.state); -}; - -/***/ }), + debug('default %s', status) -/***/ 48680: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } -var EventEmitter = __nccwpck_require__(28614).EventEmitter - , util = __nccwpck_require__(31669); + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } -function OctetParser(options){ - if(!(this instanceof OctetParser)) return new OctetParser(options); - EventEmitter.call(this); + // send response + send(req, res, status, headers, msg) + } } -util.inherits(OctetParser, EventEmitter); +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ -exports.h = OctetParser; +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } -OctetParser.prototype.write = function(buffer) { - this.emit('data', buffer); - return buffer.length; -}; + var headers = Object.create(null) + var keys = Object.keys(err.headers) -OctetParser.prototype.end = function() { - this.emit('end'); -}; + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + return headers +} -/***/ }), +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ -/***/ 80825: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function getErrorMessage (err, status, env) { + var msg -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack -// This is a buffering parser, not quite as nice as the multipart one. -// If I find time I'll rewrite this to be fully streaming as well -var querystring = __nccwpck_require__(71191); + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } -function QuerystringParser(maxKeys) { - this.maxKeys = maxKeys; - this.buffer = ''; + return msg || statuses[status] } -exports.l = QuerystringParser; -QuerystringParser.prototype.write = function(buffer) { - this.buffer += buffer.toString('ascii'); - return buffer.length; -}; +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ -QuerystringParser.prototype.end = function() { - var fields = querystring.parse(this.buffer, '&', '=', { maxKeys: this.maxKeys }); - for (var field in fields) { - this.onField(field, fields[field]); +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status } - this.buffer = ''; - - this.onEnd(); -}; - - - -/***/ }), - -/***/ 46868: -/***/ ((module) => { - -"use strict"; -/*! - * forwarded - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + return undefined +} /** - * Module exports. - * @public + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private */ -module.exports = forwarded +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} /** - * Get all addresses in the request, using the `X-Forwarded-For` header. + * Get status code from response. * - * @param {object} req - * @return {array} - * @public + * @param {OutgoingMessage} res + * @return {number} + * @private */ -function forwarded (req) { - if (!req) { - throw new TypeError('argument req is required') - } +function getResponseStatusCode (res) { + var status = res.statusCode - // simple header parsing - var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') - var socketAddr = req.connection.remoteAddress - var addrs = [socketAddr].concat(proxyAddrs) + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } - // return all addresses - return addrs + return status } /** - * Parse the X-Forwarded-For header. + * Determine if the response headers have been sent. * - * @param {string} header + * @param {object} res + * @returns {boolean} * @private */ -function parse (header) { - var end = header.length - var list = [] - var start = header.length - - // gather addresses, backwards - for (var i = header.length - 1; i >= 0; i--) { - switch (header.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i - } - break - case 0x2c: /* , */ - if (start !== end) { - list.push(header.substring(start, end)) - } - start = end = i - break - default: - start = i - break +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + res.statusMessage = statuses[status] + + // response headers + setHeaders(res, headers) + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return } + + res.end(body, 'utf8') } - // final address - if (start !== end) { - list.push(header.substring(start, end)) + if (isFinished(req)) { + write() + return } - return list + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() } +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ -/***/ }), +function setHeaders (res, headers) { + if (!headers) { + return + } -/***/ 83136: -/***/ ((module) => { + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} -"use strict"; -/*! - * fresh - * Copyright(c) 2012 TJ Holowaychuk - * Copyright(c) 2016-2017 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ }), +/***/ 56401: +/***/ ((module, exports, __nccwpck_require__) => { /** - * RegExp to check for no-cache token in Cache-Control. - * @private + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. */ -var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ +exports = module.exports = __nccwpck_require__(60545); +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(); /** - * Module exports. - * @public + * Colors. */ -module.exports = fresh +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; /** - * Check freshness of the response using request and response headers. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * @param {Object} reqHeaders - * @param {Object} resHeaders - * @return {Boolean} - * @public + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -function fresh (reqHeaders, resHeaders) { - // fields - var modifiedSince = reqHeaders['if-modified-since'] - var noneMatch = reqHeaders['if-none-match'] - - // unconditional request - if (!modifiedSince && !noneMatch) { - return false +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; } - // Always return stale when Cache-Control: no-cache - // to support end-to-end reload requests - // https://tools.ietf.org/html/rfc2616#section-14.9.4 - var cacheControl = reqHeaders['cache-control'] - if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { - return false + // 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+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; } +}; - // if-none-match - if (noneMatch && noneMatch !== '*') { - var etag = resHeaders['etag'] - if (!etag) { - return false - } +/** + * Colorize log arguments if enabled. + * + * @api public + */ - var etagStale = true - var matches = parseTokenList(noneMatch) - for (var i = 0; i < matches.length; i++) { - var match = matches[i] - if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { - etagStale = false - break - } - } +function formatArgs(args) { + var useColors = this.useColors; - if (etagStale) { - return false - } - } + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - // if-modified-since - if (modifiedSince) { - var lastModified = resHeaders['last-modified'] - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + if (!useColors) return; - if (modifiedStale) { - return false + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // 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; } - } + }); - return true + args.splice(lastC, 0, c); } /** - * Parse an HTTP Date into a number. + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". * - * @param {string} date - * @private + * @api public */ -function parseHttpDate (date) { - var timestamp = date && Date.parse(date) +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); +} - // istanbul ignore next: guard against date.js Date.parse patching - return typeof timestamp === 'number' - ? timestamp - : NaN +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} } /** - * Parse a HTTP token list. + * Load `namespaces`. * - * @param {string} str - * @private + * @return {String} returns the previously persisted debug modes + * @api private */ -function parseTokenList (str) { - var end = 0 - var list = [] - var start = 0 +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - // gather tokens - for (var i = 0, len = str.length; i < len; i++) { - switch (str.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i + 1 - } - break - case 0x2c: /* , */ - list.push(str.substring(start, end)) - start = end = i + 1 - break - default: - end = i + 1 - break - } + // 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; } - // final token - list.push(str.substring(start, end)) - - return list + return r; } +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ -/***/ }), - -/***/ 19320: -/***/ ((module) => { +exports.enable(load()); -"use strict"; +/** + * 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) {} +} -/* eslint no-invalid-this: 1 */ -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; +/***/ }), -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); +/***/ 60545: +/***/ ((module, exports, __nccwpck_require__) => { - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(80761); - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } +/** + * The currently active debug mode names, and names to skip. + */ - return bound; -}; +exports.names = []; +exports.skips = []; +/** + * 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". + */ -/***/ }), +exports.formatters = {}; -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Previous log timestamp. + */ -"use strict"; +var prevTime; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -var implementation = __nccwpck_require__(19320); +function selectColor(namespace) { + var hash = 0, i; -module.exports = Function.prototype.bind || implementation; + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + return exports.colors[Math.abs(hash) % exports.colors.length]; +} -/***/ }), +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -/***/ 31621: -/***/ ((module) => { +function createDebug(namespace) { -"use strict"; + function debug() { + // disabled? + if (!debug.enabled) return; + var self = debug; -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + // 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]; + } -/***/ }), + args[0] = exports.coerce(args[0]); -/***/ 76339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } -"use strict"; + // 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); + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -var bind = __nccwpck_require__(88334); + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -/***/ }), - -/***/ 95193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * http-errors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ - + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + return debug; +} /** - * Module dependencies. - * @private + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public */ -var deprecate = __nccwpck_require__(18883)('http-errors') -var setPrototypeOf = __nccwpck_require__(40414) -var statuses = __nccwpck_require__(57415) -var inherits = __nccwpck_require__(44124) -var toIdentifier = __nccwpck_require__(46399) +function enable(namespaces) { + exports.save(namespaces); -/** - * Module exports. - * @public - */ + exports.names = []; + exports.skips = []; -module.exports = createError -module.exports.HttpError = createHttpErrorConstructor() + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; -// Populate exports for all constructors -populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + 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 + '$')); + } + } +} /** - * Get the code class of a status code. - * @private + * Disable debug output. + * + * @api public */ -function codeClass (status) { - return Number(String(status).charAt(0) + '00') +function disable() { + exports.enable(''); } /** - * Create a new HTTP Error. + * Returns true if the given mode name is enabled, false otherwise. * - * @returns {Error} - * @public + * @param {String} name + * @return {Boolean} + * @api public */ -function createError () { - // so much arity going on ~_~ - var err - var msg - var status = 500 - var props = {} - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i] - if (arg instanceof Error) { - err = arg - status = err.status || err.statusCode || status - continue +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; } - switch (typeof arg) { - case 'string': - msg = arg - break - case 'number': - status = arg - if (i !== 0) { - deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') - } - break - case 'object': - props = arg - break + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } } + return false; +} - if (typeof status === 'number' && (status < 400 || status >= 600)) { - deprecate('non-error status code; use only 4xx or 5xx status codes') - } +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - if (typeof status !== 'number' || - (!statuses[status] && (status < 400 || status >= 600))) { - status = 500 - } +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} - // constructor - var HttpError = createError[status] || createError[codeClass(status)] - if (!err) { - // create error - err = HttpError - ? new HttpError(msg) - : new Error(msg || statuses[status]) - Error.captureStackTrace(err, createError) - } +/***/ }), - if (!HttpError || !(err instanceof HttpError) || err.status !== status) { - // add properties to generic error - err.expose = status < 500 - err.status = err.statusCode = status - } +/***/ 65612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var key in props) { - if (key !== 'status' && key !== 'statusCode') { - err[key] = props[key] - } - } +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ - return err +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(56401); +} else { + module.exports = __nccwpck_require__(4706); } + +/***/ }), + +/***/ 4706: +/***/ ((module, exports, __nccwpck_require__) => { + /** - * Create HTTP error abstract base class. - * @private + * Module dependencies. */ -function createHttpErrorConstructor () { - function HttpError () { - throw new TypeError('cannot construct abstract class') - } +var tty = __nccwpck_require__(33867); +var util = __nccwpck_require__(31669); - inherits(HttpError, Error) +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - return HttpError -} +exports = module.exports = __nccwpck_require__(60545); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; /** - * Create a constructor for a client error. - * @private + * Colors. */ -function createClientErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' +exports.colors = [6, 2, 3, 4, 5, 1]; - function ClientError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - // capture a stack trace to the construction point - Error.captureStackTrace(err, ClientError) +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - // adjust the [[Prototype]] - setPrototypeOf(err, ClientError.prototype) + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) + obj[prop] = val; + return obj; +}, {}); - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - return err - } +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - inherits(ClientError, HttpError) - nameFunc(ClientError, className) +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} - ClientError.prototype.status = code - ClientError.prototype.statusCode = code - ClientError.prototype.expose = true +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - return ClientError +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); } /** - * Create a constructor for a server error. - * @private + * Map %o to `util.inspect()`, all on a single line. */ -function createServerErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; - function ServerError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - // capture a stack trace to the construction point - Error.captureStackTrace(err, ServerError) +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - // adjust the [[Prototype]] - setPrototypeOf(err, ServerError.prototype) +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - return err + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } +} - inherits(ServerError, HttpError) - nameFunc(ServerError, className) +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ - ServerError.prototype.status = code - ServerError.prototype.statusCode = code - ServerError.prototype.expose = false +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} - return ServerError +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } } /** - * Set the name of a function, if possible. - * @private + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -function nameFunc (func, name) { - var desc = Object.getOwnPropertyDescriptor(func, 'name') +function load() { + return process.env.DEBUG; +} - if (desc && desc.configurable) { - desc.value = name - Object.defineProperty(func, 'name', desc) +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = __nccwpck_require__(35747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(11631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; } /** - * Populate the exports object with constructors for every error class. - * @private + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function populateConstructorExports (exports, codes, HttpError) { - codes.forEach(function forEachCode (code) { - var CodeError - var name = toIdentifier(statuses[code]) +function init (debug) { + debug.inspectOpts = {}; - switch (codeClass(code)) { - case 400: - CodeError = createClientErrorConstructor(HttpError, name, code) - break - case 500: - CodeError = createServerErrorConstructor(HttpError, name, code) - break - } + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - if (CodeError) { - // export the constructor - exports[code] = CodeError - exports[name] = CodeError - } - }) +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - // backwards-compatibility - exports["I'mateapot"] = deprecate.function(exports.ImATeapot, - '"I\'mateapot"; use "ImATeapot" instead') -} +exports.enable(load()); /***/ }), -/***/ 15098: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 80761: +/***/ ((module) => { -"use strict"; +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __importDefault(__nccwpck_require__(11631)); -const tls_1 = __importDefault(__nccwpck_require__(4016)); -const url_1 = __importDefault(__nccwpck_require__(78835)); -const assert_1 = __importDefault(__nccwpck_require__(42357)); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const agent_base_1 = __nccwpck_require__(49690); -const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595)); -const debug = debug_1.default('https-proxy-agent:agent'); /** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * Parse or format the given `val`. * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. + * Options: * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. + * - `long` verbose formatting [false] * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} * @api public */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === 'string') { - opts = url_1.default.parse(_opts); - } - else { - opts = _opts; - } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); - } - debug('creating new HttpsProxyAgent instance: %o', opts); - super(opts); - const proxy = Object.assign({}, opts); - // If `true`, then connect to the proxy server over TLS. - // Defaults to `false`. - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - // Prefer `hostname` over `host`, and set the `port` if needed. - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === 'string') { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - // ALPN is supported by Node.js >= v5. - // attempt to negotiate http/1.1 for proxy servers that support http/2 - if (this.secureProxy && !('ALPNProtocols' in proxy)) { - proxy.ALPNProtocols = ['http 1.1']; - } - if (proxy.host && proxy.path) { - // If both a `host` and `path` are specified then it's most likely - // the result of a `url.parse()` call... we need to remove the - // `path` portion so that `net.connect()` doesn't attempt to open - // that as a Unix socket file. - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - * - * @api protected - */ - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - // Create a socket connection to the proxy server. - let socket; - if (secureProxy) { - debug('Creating `tls.Socket`: %o', proxy); - socket = tls_1.default.connect(proxy); - } - else { - debug('Creating `net.Socket`: %o', proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.auth) { - headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; - } - // The `Host` header should only include the port - // number when it is not the default port. - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = 'close'; - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r\n`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - const servername = opts.servername || opts.host; - if (!servername) { - throw new Error('Could not determine "servername"'); - } - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, - servername })); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net_1.default.Socket(); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('replaying proxy buffer for failed request'); - assert_1.default(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); - } -} -exports.default = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function isDefaultPort(port, secure) { - return Boolean((!secure && port === 80) || (secure && port === 443)); -} -function isHTTPS(protocol) { - return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=agent.js.map -/***/ }), +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; -/***/ 77219: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ -"use strict"; +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const agent_1 = __importDefault(__nccwpck_require__(15098)); -function createHttpsProxyAgent(opts) { - return new agent_1.default(opts); +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } -(function (createHttpsProxyAgent) { - createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent.prototype = agent_1.default.prototype; -})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); -module.exports = createHttpsProxyAgent; -//# sourceMappingURL=index.js.map -/***/ }), +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -/***/ 595: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} -"use strict"; +/** + * Pluralization helper. + */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('close', onclose); - socket.removeListener('readable', read); - } - function onclose(err) { - debug('onclose had error %o', err); - } - function onend() { - debug('onend'); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); - const statusCode = +firstLine.split(' ')[1]; - debug('got proxy server response: %o', firstLine); - resolve({ - statusCode, - buffered - }); - } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; } -exports.default = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map + /***/ }), -/***/ 39695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 35298: +/***/ ((module) => { "use strict"; -var Buffer = __nccwpck_require__(15118).Buffer; -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. +// You may be tempted to copy and paste this, +// but take a look at the commit history first, +// this is a moving target so relying on the module +// is the best way to make sure the optimization +// method is kept up to date and compatible with +// every Node version. -exports._dbcs = DBCSCodec; +function flatstr (s) { + s | 0 + return s +} -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; +module.exports = flatstr -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; +/***/ }), +/***/ 68329: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); - // Load tables. - var mappingTable = codecOptions.table(); +var util = __nccwpck_require__(31669), + fs = __nccwpck_require__(35747), + EventEmitter = __nccwpck_require__(28614).EventEmitter, + crypto = __nccwpck_require__(76417); +function File(properties) { + EventEmitter.call(this); - // Decode tables: MBCS -> Unicode. + this.size = 0; + this.path = null; + this.name = null; + this.type = null; + this.hash = null; + this.lastModifiedDate = null; - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + this._writeStream = null; + + for (var key in properties) { + this[key] = properties[key]; + } - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; + if(typeof this.hash === 'string') { + this.hash = crypto.createHash(properties.hash); + } else { + this.hash = null; + } +} +module.exports = File; +util.inherits(File, EventEmitter); - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); +File.prototype.open = function() { + this._writeStream = new fs.WriteStream(this.path); +}; - this.defaultCharUnicode = iconv.defaultCharUnicode; +File.prototype.toJSON = function() { + var json = { + size: this.size, + path: this.path, + name: this.name, + type: this.type, + mtime: this.lastModifiedDate, + length: this.length, + filename: this.filename, + mime: this.mime + }; + if (this.hash && this.hash != "") { + json.hash = this.hash; + } + return json; +}; - - // Encode tables: Unicode -> DBCS. +File.prototype.write = function(buffer, cb) { + var self = this; + if (self.hash) { + self.hash.update(buffer); + } - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; + if (this._writeStream.closed) { + return cb(); + } - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; - } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); + this._writeStream.write(buffer, function() { + self.lastModifiedDate = new Date(); + self.size += buffer.length; + self.emit('progress', self.size); + cb(); + }); +}; - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); - } +File.prototype.end = function(cb) { + var self = this; + if (self.hash) { + self.hash = self.hash.digest('hex'); + } + this._writeStream.end(function() { + self.emit('end'); + cb(); + }); +}; - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); +/***/ }), - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. +/***/ 7973: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); - - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); - - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; - var secondByteNode = this.decodeTables[secondByteNodeIdx]; - for (var j = 0x30; j <= 0x39; j++) - secondByteNode[j] = NODE_START - thirdByteNodeIdx; - } - for (var i = 0x81; i <= 0xFE; i++) - thirdByteNode[i] = NODE_START - fourthByteNodeIdx; - for (var i = 0x30; i <= 0x39; i++) - fourthByteNode[i] = GB18030_CODE - } -} - -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; - -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); - - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; - } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); - } - return node; -} +var crypto = __nccwpck_require__(76417); +var fs = __nccwpck_require__(35747); +var util = __nccwpck_require__(31669), + path = __nccwpck_require__(85622), + File = __nccwpck_require__(68329), + MultipartParser = __nccwpck_require__(31323).MultipartParser, + QuerystringParser = __nccwpck_require__(80825)/* .QuerystringParser */ .l, + OctetParser = __nccwpck_require__(48680)/* .OctetParser */ .h, + JSONParser = __nccwpck_require__(715)/* .JSONParser */ .c, + StringDecoder = __nccwpck_require__(24304).StringDecoder, + EventEmitter = __nccwpck_require__(28614).EventEmitter, + Stream = __nccwpck_require__(92413).Stream, + os = __nccwpck_require__(12087); +function IncomingForm(opts) { + if (!(this instanceof IncomingForm)) return new IncomingForm(opts); + EventEmitter.call(this); -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); + opts=opts||{}; - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; + this.error = null; + this.ended = false; - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + this.maxFields = opts.maxFields || 1000; + this.maxFieldsSize = opts.maxFieldsSize || 20 * 1024 * 1024; + this.maxFileSize = opts.maxFileSize || 200 * 1024 * 1024; + this.keepExtensions = opts.keepExtensions || false; + this.uploadDir = opts.uploadDir || (os.tmpdir && os.tmpdir()) || os.tmpDir(); + this.encoding = opts.encoding || 'utf-8'; + this.headers = null; + this.type = null; + this.hash = opts.hash || false; + this.multiples = opts.multiples || false; - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char - } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); - } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} + this.bytesReceived = null; + this.bytesExpected = null; -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} + this._parser = null; + this._flushing = 0; + this._fieldsSize = 0; + this._fileSize = 0; + this.openedFiles = []; -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; + return this; } +util.inherits(IncomingForm, EventEmitter); +exports.c = IncomingForm; -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; +IncomingForm.prototype.parse = function(req, cb) { + this.pause = function() { + try { + req.pause(); + } catch (err) { + // the stream was destroyed + if (!this.ended) { + // before it was completed, crash & burn + this._error(err); + } + return false; } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); + return true; + }; + + this.resume = function() { + try { + req.resume(); + } catch (err) { + // the stream was destroyed + if (!this.ended) { + // before it was completed, crash & burn + this._error(err); + } + return false; } - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; - else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal + return true; + }; + + // Setup callback first, so we don't miss anything from data events emitted + // immediately. + if (cb) { + var fields = {}, files = {}; + this + .on('field', function(name, value) { + fields[name] = value; + }) + .on('file', function(name, file) { + if (this.multiples) { + if (files[name]) { + if (!Array.isArray(files[name])) { + files[name] = [files[name]]; + } + files[name].push(file); + } else { + files[name] = file; + } + } else { + files[name] = file; } - } + }) + .on('error', function(err) { + cb(err, fields, files); + }) + .on('end', function() { + cb(null, fields, files); + }); + } - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} + // Parse headers and setup the parser, ready to start listening for data. + this.writeHeaders(req.headers); -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; + // Start listening for data. + var self = this; + req + .on('error', function(err) { + self._error(err); + }) + .on('aborted', function() { + self.emit('aborted'); + self._error(new Error('Request aborted')); + }) + .on('data', function(buffer) { + self.write(buffer); + }) + .on('end', function() { + if (self.error) { + return; + } - if (uCode >= 0) - this._setEncodeChar(uCode, mbCode); - else if (uCode <= NODE_START) - this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); - else if (uCode <= SEQ_START) - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); - } -} + var err = self._parser.end(); + if (err) { + self._error(err); + } + }); + return this; +}; +IncomingForm.prototype.writeHeaders = function(headers) { + this.headers = headers; + this._parseContentLength(); + this._parseContentType(); +}; -// == Encoder ================================================================== +IncomingForm.prototype.write = function(buffer) { + if (this.error) { + return; + } + if (!this._parser) { + this._error(new Error('uninitialized parser')); + return; + } -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; -} + this.bytesReceived += buffer.length; + this.emit('progress', this.bytesReceived, this.bytesExpected); -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; + var bytesParsed = this._parser.write(buffer); + if (bytesParsed !== buffer.length) { + this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); + } - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } + return bytesParsed; +}; - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } +IncomingForm.prototype.pause = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; +IncomingForm.prototype.resume = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; +IncomingForm.prototype.onPart = function(part) { + // this method can be overwritten by the user + this.handlePart(part); +}; - } else if (resCode == undefined) { // Current character is not part of the sequence. +IncomingForm.prototype.handlePart = function(part) { + var self = this; - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. + // This MUST check exactly for undefined. You can not change it to !part.filename. + if (part.filename === undefined) { + var value = '' + , decoder = new StringDecoder(this.encoding); - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } + part.on('data', function(buffer) { + self._fieldsSize += buffer.length; + if (self._fieldsSize > self.maxFieldsSize) { + self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); + return; + } + value += decoder.write(buffer); + }); - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } + part.on('end', function() { + self.emit('field', part.name, value); + }); + return; + } - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } - } + this._flushing++; - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} + var file = new File({ + path: this._uploadPath(part.filename), + name: part.filename, + type: part.mime, + hash: self.hash + }); -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. + this.emit('fileBegin', part.name, file); - var newBuf = Buffer.alloc(10), j = 0; + file.open(); + this.openedFiles.push(file); - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; + part.on('data', function(buffer) { + self._fileSize += buffer.length; + if (self._fileSize > self.maxFileSize) { + self._error(new Error('maxFileSize exceeded, received '+self._fileSize+' bytes of file data')); + return; + } + if (buffer.length == 0) { + return; } + self.pause(); + file.write(buffer, function() { + self.resume(); + }); + }); - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; + part.on('end', function() { + file.end(function() { + self._flushing--; + self.emit('file', part.name, file); + self._maybeEnd(); + }); + }); +}; + +function dummyParser(self) { + return { + end: function () { + self.ended = true; + self._maybeEnd(); + return null; } - - return newBuf.slice(0, j); + }; } -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; - +IncomingForm.prototype._parseContentType = function() { + if (this.bytesExpected === 0) { + this._parser = dummyParser(this); + return; + } -// == Decoder ================================================================== - -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); - - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} - -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, - seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. - uCode; + if (!this.headers['content-type']) { + this._error(new Error('bad content-type header, no content-type')); + return; + } - if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. - prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + if (this.headers['content-type'].match(/octet-stream/i)) { + this._initOctetStream(); + return; + } - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; + if (this.headers['content-type'].match(/urlencoded/i)) { + this._initUrlencoded(); + return; + } - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). - uCode = this.defaultCharUnicode.charCodeAt(0); - } - else if (uCode === GB18030_CODE) { - var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + if (this.headers['content-type'].match(/multipart/i)) { + var m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (m) { + this._initMultipart(m[1] || m[2]); + } else { + this._error(new Error('bad content-type header, no multipart boundary')); + } + return; + } - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode > 0xFFFF) { - uCode -= 0x10000; - var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; + if (this.headers['content-type'].match(/json/i)) { + this._initJSONencoded(); + return; + } - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; + this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); +}; - // Reset trie node. - nodeIdx = 0; seqStart = i+1; - } +IncomingForm.prototype._error = function(err) { + if (this.error || this.ended) { + return; + } - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); -} + this.error = err; + this.emit('error', err); -DBCSDecoder.prototype.end = function() { - var ret = ''; + if (Array.isArray(this.openedFiles)) { + this.openedFiles.forEach(function(file) { + file._writeStream.destroy(); + setTimeout(fs.unlink, 0, file.path, function(error) { }); + }); + } +}; - // Try to parse all remaining chars. - while (this.prevBuf.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var buf = this.prevBuf.slice(1); +IncomingForm.prototype._parseContentLength = function() { + this.bytesReceived = 0; + if (this.headers['content-length']) { + this.bytesExpected = parseInt(this.headers['content-length'], 10); + } else if (this.headers['transfer-encoding'] === undefined) { + this.bytesExpected = 0; + } - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); - } + if (this.bytesExpected !== null) { + this.emit('progress', this.bytesReceived, this.bytesExpected); + } +}; - this.nodeIdx = 0; - return ret; -} +IncomingForm.prototype._newParser = function() { + return new MultipartParser(); +}; -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; +IncomingForm.prototype._initMultipart = function(boundary) { + this.type = 'multipart'; - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + Math.floor((r-l+1)/2); - if (table[mid] <= val) - l = mid; - else - r = mid; - } - return l; -} + var parser = new MultipartParser(), + self = this, + headerField, + headerValue, + part; + parser.initWithBoundary(boundary); + parser.onPartBegin = function() { + part = new Stream(); + part.readable = true; + part.headers = {}; + part.name = null; + part.filename = null; + part.mime = null; -/***/ }), + part.transferEncoding = 'binary'; + part.transferBuffer = ''; -/***/ 91386: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + headerField = ''; + headerValue = ''; + }; -"use strict"; + parser.onHeaderField = function(b, start, end) { + headerField += b.toString(self.encoding, start, end); + }; + parser.onHeaderValue = function(b, start, end) { + headerValue += b.toString(self.encoding, start, end); + }; -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. + parser.onHeaderEnd = function() { + headerField = headerField.toLowerCase(); + part.headers[headerField] = headerValue; -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + var m = headerValue.match(/\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i); + if (headerField == 'content-disposition') { + if (m) { + part.name = m[2] || m[3] || ''; + } - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + part.filename = self._fileName(headerValue); + } else if (headerField == 'content-type') { + part.mime = headerValue; + } else if (headerField == 'content-transfer-encoding') { + part.transferEncoding = headerValue.toLowerCase(); + } - 'shiftjis': { - type: '_dbcs', - table: function() { return __nccwpck_require__(64108) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', + headerField = ''; + headerValue = ''; + }; - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(72417) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, + parser.onHeadersEnd = function() { + switch(part.transferEncoding){ + case 'binary': + case '7bit': + case '8bit': + parser.onPartData = function(b, start, end) { + part.emit('data', b.slice(start, end)); + }; - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + parser.onPartEnd = function() { + part.emit('end'); + }; + break; + case 'base64': + parser.onPartData = function(b, start, end) { + part.transferBuffer += b.slice(start, end).toString('ascii'); - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + /* + four bytes (chars) in base64 converts to three bytes in binary + encoding. So we should always work with a number of bytes that + can be divided by 4, it will result in a number of buytes that + can be divided vy 3. + */ + var offset = parseInt(part.transferBuffer.length / 4, 10) * 4; + part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64')); + part.transferBuffer = part.transferBuffer.substring(offset); + }; - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', + parser.onPartEnd = function() { + part.emit('data', new Buffer(part.transferBuffer, 'base64')); + part.emit('end'); + }; + break; - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803) }, - }, + default: + return self._error(new Error('unknown transfer-encoding')); + } - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', + self.onPart(part); + }; - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, - gb18030: function() { return __nccwpck_require__(86351) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, - 'chinese': 'gb18030', + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; + this._parser = parser; +}; - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __nccwpck_require__(87013) }, - }, +IncomingForm.prototype._fileName = function(headerValue) { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + var m = headerValue.match(/\bfilename=("(.*?)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))($|;\s)/i); + if (!m) return; - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', + var match = m[2] || m[3] || ''; + var filename = match.substr(match.lastIndexOf('\\') + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#([\d]{4});/g, function(m, code) { + return String.fromCharCode(code); + }); + return filename; +}; +IncomingForm.prototype._initUrlencoded = function() { + this.type = 'urlencoded'; - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + var parser = new QuerystringParser(this.maxFields) + , self = this; - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(33104) }, - }, + parser.onField = function(key, val) { + self.emit('field', key, val); + }; - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return __nccwpck_require__(33104).concat(__nccwpck_require__(43612)) }, - encodeSkipVals: [0xa2cc], - }, + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', + this._parser = parser; }; +IncomingForm.prototype._initOctetStream = function() { + this.type = 'octet-stream'; + var filename = this.headers['x-file-name']; + var mime = this.headers['content-type']; -/***/ }), + var file = new File({ + path: this._uploadPath(filename), + name: filename, + type: mime + }); -/***/ 82733: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.emit('fileBegin', filename, file); + file.open(); + this.openedFiles.push(file); + this._flushing++; -"use strict"; + var self = this; + self._parser = new OctetParser(); -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __nccwpck_require__(12376), - __nccwpck_require__(11155), - __nccwpck_require__(51644), - __nccwpck_require__(26657), - __nccwpck_require__(41080), - __nccwpck_require__(21012), - __nccwpck_require__(39695), - __nccwpck_require__(91386), -]; + //Keep track of writes that haven't finished so we don't emit the file before it's done being written + var outstandingWrites = 0; -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; -} + self._parser.on('data', function(buffer){ + self.pause(); + outstandingWrites++; + file.write(buffer, function() { + outstandingWrites--; + self.resume(); -/***/ }), + if(self.ended){ + self._parser.emit('doneWritingFile'); + } + }); + }); -/***/ 12376: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + self._parser.on('end', function(){ + self._flushing--; + self.ended = true; -"use strict"; + var done = function(){ + file.end(function() { + self.emit('file', 'file', file); + self._maybeEnd(); + }); + }; -var Buffer = __nccwpck_require__(15118).Buffer; + if(outstandingWrites === 0){ + done(); + } else { + self._parser.once('doneWritingFile', done); + } + }); +}; -// Export Node.js internal encodings. +IncomingForm.prototype._initJSONencoded = function() { + this.type = 'json'; -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", + var parser = new JSONParser(this) + , self = this; - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", + parser.onField = function(key, val) { + self.emit('field', key, val); + }; - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; - // Codec. - _internal: InternalCodec, + this._parser = parser; }; -//------------------------------------------------------------------------------ +IncomingForm.prototype._uploadPath = function(filename) { + var buf = crypto.randomBytes(16); + var name = 'upload_' + buf.toString('hex'); -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; + if (this.keepExtensions) { + var ext = path.extname(filename); + ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; + name += ext; + } - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } -} + return path.join(this.uploadDir, name); +}; -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; +IncomingForm.prototype._maybeEnd = function() { + if (!this.ended || this._flushing || this.error) { + return; + } -//------------------------------------------------------------------------------ + this.emit('end'); +}; -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = __nccwpck_require__(24304).StringDecoder; -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; +/***/ }), +/***/ 95265: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); -} +var IncomingForm = __nccwpck_require__(7973)/* .IncomingForm */ .c; +IncomingForm.IncomingForm = IncomingForm; +module.exports = IncomingForm; -InternalDecoder.prototype = StringDecoder.prototype; +/***/ }), -//------------------------------------------------------------------------------ -// Encoder is mostly trivial +/***/ 715: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} +var Buffer = __nccwpck_require__(64293).Buffer; -InternalEncoder.prototype.end = function() { +function JSONParser(parent) { + this.parent = parent; + this.chunks = []; + this.bytesWritten = 0; } +exports.c = JSONParser; +JSONParser.prototype.write = function(buffer) { + this.bytesWritten += buffer.length; + this.chunks.push(buffer); + return buffer.length; +}; -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. +JSONParser.prototype.end = function() { + try { + var fields = JSON.parse(Buffer.concat(this.chunks)); + for (var field in fields) { + this.onField(field, fields[field]); + } + } catch (e) { + this.parent.emit('error', e); + } + this.data = null; -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} + this.onEnd(); +}; -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); - return Buffer.from(str, "base64"); -} +/***/ }), -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} +/***/ 31323: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var Buffer = __nccwpck_require__(64293).Buffer, + s = 0, + S = + { PARSER_UNINITIALIZED: s++, + START: s++, + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + PART_END: s++, + END: s++ + }, -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. + f = 1, + F = + { PART_BOUNDARY: f, + LAST_BOUNDARY: f *= 2 + }, -function InternalEncoderCesu8(options, codec) { -} + LF = 10, + CR = 13, + SPACE = 32, + HYPHEN = 45, + COLON = 58, + A = 97, + Z = 122, -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - } - return buf.slice(0, bufIdx); -} + lower = function(c) { + return c | 0x20; + }; -InternalEncoderCesu8.prototype.end = function() { +for (s in S) { + exports[s] = S[s]; } -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ +function MultipartParser() { + this.boundary = null; + this.boundaryChars = null; + this.lookbehind = null; + this.state = S.PARSER_UNINITIALIZED; -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; + this.index = null; + this.flags = 0; } +exports.MultipartParser = MultipartParser; -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } +MultipartParser.stateToString = function(stateNumber) { + for (var state in S) { + var number = S[state]; + if (number === stateNumber) return state; + } +}; - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; - } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; - } - } - } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; -} +MultipartParser.prototype.initWithBoundary = function(str) { + this.boundary = new Buffer(str.length+4); + this.boundary.write('\r\n--', 0); + this.boundary.write(str, 4); + this.lookbehind = new Buffer(this.boundary.length+8); + this.state = S.START; -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; -} + this.boundaryChars = {}; + for (var i = 0; i < this.boundary.length; i++) { + this.boundaryChars[this.boundary[i]] = true; + } +}; +MultipartParser.prototype.write = function(buffer) { + var self = this, + i = 0, + len = buffer.length, + prevIndex = this.index, + index = this.index, + state = this.state, + flags = this.flags, + lookbehind = this.lookbehind, + boundary = this.boundary, + boundaryChars = this.boundaryChars, + boundaryLength = this.boundary.length, + boundaryEnd = boundaryLength - 1, + bufferLength = buffer.length, + c, + cl, -/***/ }), + mark = function(name) { + self[name+'Mark'] = i; + }, + clear = function(name) { + delete self[name+'Mark']; + }, + callback = function(name, buffer, start, end) { + if (start !== undefined && start === end) { + return; + } -/***/ 26657: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); + if (callbackSymbol in self) { + self[callbackSymbol](buffer, start, end); + } + }, + dataCallback = function(name, clear) { + var markSymbol = name+'Mark'; + if (!(markSymbol in self)) { + return; + } -"use strict"; + if (!clear) { + callback(name, buffer, self[markSymbol], buffer.length); + self[markSymbol] = 0; + } else { + callback(name, buffer, self[markSymbol], i); + delete self[markSymbol]; + } + }; -var Buffer = __nccwpck_require__(15118).Buffer; + for (i = 0; i < len; i++) { + c = buffer[i]; + switch (state) { + case S.PARSER_UNINITIALIZED: + return i; + case S.START: + index = 0; + state = S.START_BOUNDARY; + case S.START_BOUNDARY: + if (index == boundary.length - 2) { + if (c == HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c != CR) { + return i; + } + index++; + break; + } else if (index - 1 == boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c == HYPHEN){ + callback('end'); + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c == LF) { + index = 0; + callback('partBegin'); + state = S.HEADER_FIELD_START; + } else { + return i; + } + break; + } -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). + if (c != boundary[index+2]) { + index = -2; + } + if (c == boundary[index+2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark('headerField'); + index = 0; + case S.HEADER_FIELD: + if (c == CR) { + clear('headerField'); + state = S.HEADERS_ALMOST_DONE; + break; + } -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; - } + index++; + if (c == HYPHEN) { + break; + } - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + if (c == COLON) { + if (index == 1) { + // empty header field + return i; + } + dataCallback('headerField', true); + state = S.HEADER_VALUE_START; + break; + } - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + cl = lower(c); + if (cl < A || cl > Z) { + return i; + } + break; + case S.HEADER_VALUE_START: + if (c == SPACE) { + break; + } - this.encodeBuf = encodeBuf; -} + mark('headerValue'); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c == CR) { + dataCallback('headerValue', true); + callback('headerEnd'); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c != LF) { + return i; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c != LF) { + return i; + } -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; + callback('headersEnd'); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark('partData'); + case S.PART_DATA: + prevIndex = index; + if (index === 0) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while (i < bufferLength && !(buffer[i] in boundaryChars)) { + i += boundaryLength; + } + i -= boundaryEnd; + c = buffer[i]; + } -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} + if (index < boundary.length) { + if (boundary[index] == c) { + if (index === 0) { + dataCallback('partData', true); + } + index++; + } else { + index = 0; + } + } else if (index == boundary.length) { + index++; + if (c == CR) { + // CR = part boundary + flags |= F.PART_BOUNDARY; + } else if (c == HYPHEN) { + // HYPHEN = end boundary + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 == boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c == LF) { + // unset the PART_BOUNDARY flag + flags &= ~F.PART_BOUNDARY; + callback('partEnd'); + callback('partBegin'); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c == HYPHEN) { + callback('partEnd'); + callback('end'); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; -} + if (index > 0) { + // when matching a possible boundary, keep a lookbehind reference + // in case it turns out to be a false lead + lookbehind[index-1] = c; + } else if (prevIndex > 0) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + callback('partData', lookbehind, 0, prevIndex); + prevIndex = 0; + mark('partData'); -SBCSEncoder.prototype.end = function() { -} + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } + break; + case S.END: + break; + default: + return i; + } + } -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; + dataCallback('headerField'); + dataCallback('headerValue'); + dataCallback('partData'); + + this.index = index; + this.state = state; + this.flags = flags; + + return len; +}; + +MultipartParser.prototype.end = function() { + var callback = function(self, name) { + var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); + if (callbackSymbol in self) { + self[callbackSymbol](); + } + }; + if ((this.state == S.HEADER_FIELD_START && this.index === 0) || + (this.state == S.PART_DATA && this.index == this.boundary.length)) { + callback(this, 'partEnd'); + callback(this, 'end'); + } else if (this.state != S.END) { + return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); + } +}; + +MultipartParser.prototype.explain = function() { + return 'state = ' + MultipartParser.stateToString(this.state); +}; + + +/***/ }), + +/***/ 48680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var EventEmitter = __nccwpck_require__(28614).EventEmitter + , util = __nccwpck_require__(31669); + +function OctetParser(options){ + if(!(this instanceof OctetParser)) return new OctetParser(options); + EventEmitter.call(this); } -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; +util.inherits(OctetParser, EventEmitter); + +exports.h = OctetParser; + +OctetParser.prototype.write = function(buffer) { + this.emit('data', buffer); + return buffer.length; +}; + +OctetParser.prototype.end = function() { + this.emit('end'); +}; + + +/***/ }), + +/***/ 80825: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + +// This is a buffering parser, not quite as nice as the multipart one. +// If I find time I'll rewrite this to be fully streaming as well +var querystring = __nccwpck_require__(71191); + +function QuerystringParser(maxKeys) { + this.maxKeys = maxKeys; + this.buffer = ''; +} +exports.l = QuerystringParser; + +QuerystringParser.prototype.write = function(buffer) { + this.buffer += buffer.toString('ascii'); + return buffer.length; +}; + +QuerystringParser.prototype.end = function() { + var fields = querystring.parse(this.buffer, '&', '=', { maxKeys: this.maxKeys }); + for (var field in fields) { + this.onField(field, fields[field]); + } + this.buffer = ''; + + this.onEnd(); +}; + + + +/***/ }), + +/***/ 46868: +/***/ ((module) => { + +"use strict"; +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ + +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break } - return newBuf.toString('ucs2'); + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list } -SBCSDecoder.prototype.end = function() { + +/***/ }), + +/***/ 83136: +/***/ ((module) => { + +"use strict"; +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ + +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = fresh + +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ + +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } + + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] + + if (!etag) { + return false + } + + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } + } + + if (etagStale) { + return false + } + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list } /***/ }), -/***/ 21012: +/***/ 19320: /***/ ((module) => { "use strict"; -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} +/* eslint no-invalid-this: 1 */ -/***/ }), +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; -/***/ 41080: -/***/ ((module) => { +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); -"use strict"; + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } -// Manually added data to be used by sbcs codec in addition to generated one. + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, + return bound; +}; - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", +/***/ }), - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", +/***/ 88334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", +"use strict"; - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", +var implementation = __nccwpck_require__(19320); - "cp819": "iso88591", - "ibm819": "iso88591", +module.exports = Function.prototype.bind || implementation; - "cyrillic": "iso88595", - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", +/***/ }), - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", +/***/ 67356: +/***/ ((module) => { - "hebrew": "iso88598", - "hebrew8": "iso88598", +"use strict"; - "turkish": "iso88599", - "turkish8": "iso88599", - "thai": "iso885911", - "thai8": "iso885911", +module.exports = clone - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", + return copy +} - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", +/***/ }), - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", +/***/ 77758: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - "strk10482002": "rk1048", +var fs = __nccwpck_require__(35747) +var polyfills = __nccwpck_require__(20263) +var legacy = __nccwpck_require__(73086) +var clone = __nccwpck_require__(67356) - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", +var util = __nccwpck_require__(31669) - "gb198880": "iso646cn", - "cn": "iso646cn", +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", +function noop () {} - "mac": "macintosh", - "csmacintosh": "macintosh", -}; +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + retry() + } -/***/ }), + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } -/***/ 11155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) -"use strict"; + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + retry() + } -var Buffer = __nccwpck_require__(15118).Buffer; + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js - -// == UTF16-BE codec. ========================================================== - -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} - -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf16BEEncoder() { + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(42357).equal(fs[gracefulQueue].length, 0) + }) + } } -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); } -Utf16BEEncoder.prototype.end = function() { +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; } +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch -// -- Decoding + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null -function Utf16BEDecoder() { - this.overflowByte = -1; -} + return go$readFile(path, options, cb) -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; + function go$readFile (path, options, cb) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } + return go$writeFile(path, data, options, cb) - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) } + } - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; - - return buf2.slice(0, j).toString('ucs2'); -} + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -Utf16BEDecoder.prototype.end = function() { -} + return go$appendFile(path, data, options, cb) + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) + } else { + cb = options + } + args.push(go$readdir$cb) -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + return go$readdir(args) -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + } + } -// -- Encoding (pass-through) + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) -// -- Decoding + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBytes = []; - this.initialBytesLen = 0; + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } - this.options = options || {}; - this.iconv = codec.iconv; -} + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBytes.push(buf); - this.initialBytesLen += buf.length; - - if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) - return ''; + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } - // We have enough bytes -> detect endianness. - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - this.initialBytes.length = this.initialBytesLen = 0; - } + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - return this.decoder.write(buf); -} + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } - var res = this.decoder.write(buf), - trail = this.decoder.end(); + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } - return trail ? (res + trail) : res; - } - return this.decoder.end(); -} + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; + return go$open(path, flags, mode, cb) - if (buf.length >= 2) { - // Check BOM. - if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM - enc = 'utf-16be'; - else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM - enc = 'utf-16le'; + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) else { - // No BOM found. Try to deduce encoding from initial content. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions - _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. - - for (var i = 0; i < _len; i += 2) { - if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; - if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; - } - - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } + }) } + } - return enc; + return fs } +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) +} +function retry () { + var elem = fs[gracefulQueue].shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) + } +} /***/ }), -/***/ 51644: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 73086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var Stream = __nccwpck_require__(92413).Stream -var Buffer = __nccwpck_require__(15118).Buffer; +module.exports = legacy -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; + Stream.call(this); + var self = this; -// -- Encoding + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} + options = options || {}; -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } -Utf7Encoder.prototype.end = function() { -} + if (this.encoding) this.setEncoding(this.encoding); + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } -// -- Decoding + if (this.start > this.end) { + throw new Error('start must be <= end'); + } -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + this.pos = this.start; + } -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } - // The decoder is more involved as we must handle chunks in stream. + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString(); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + Stream.call(this); - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; + this.path = path; + this.fd = null; + this.writable = true; - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); + options = options || {}; - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + this.busy = false; + this._queue = []; - return res; + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } } -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. +/***/ }), -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; -}; +/***/ 20263: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; +var constants = __nccwpck_require__(27619) +var origCwd = process.cwd +var cwd = null -// -- Encoding +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd } +try { + process.cwd() +} catch (er) {} -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } +module.exports = patch - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } +function patch (fs) { + // (re-)implement some things that are known busted or missing. - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } - } + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - return buf.slice(0, bufIdx); -} + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; - } + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - return buf.slice(0, bufIdx); -} + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } -// -- Decoding + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + // This ensures `util.promisify` works as it does for native `fs.read`. + read.__proto__ = fs$read + return read + })(fs.read) - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) } + } + return ret } + } - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } + } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - return res; -} + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } + } -/***/ }), + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true -/***/ 67961: -/***/ ((__unused_webpack_module, exports) => { + if (er.code === "ENOSYS") + return true -"use strict"; + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + return false + } +} -var BOMChar = '\uFEFF'; -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} +/***/ }), -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } +/***/ 31621: +/***/ ((module) => { - return this.encoder.write(str); -} +"use strict"; -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; -//------------------------------------------------------------------------------ -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} +/***/ }), -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; +/***/ 76339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } +"use strict"; - this.pass = true; - return res; -} -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} +var bind = __nccwpck_require__(88334); +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }), -/***/ 30393: +/***/ 95193: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ -var Buffer = __nccwpck_require__(64293).Buffer; -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer -// == Extend Node primitives to use iconv-lite ================================= -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. +/** + * Module dependencies. + * @private + */ - // Node authors rewrote Buffer internals to make it compatible with - // Uint8Array and we cannot patch key functions since then. - // Note: this does use older Buffer API on a purpose - iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); +var deprecate = __nccwpck_require__(18883)('http-errors') +var setPrototypeOf = __nccwpck_require__(40414) +var statuses = __nccwpck_require__(57415) +var inherits = __nccwpck_require__(44124) +var toIdentifier = __nccwpck_require__(46399) - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; +/** + * Module exports. + * @public + */ - if (!iconv.supportsNodeEncodingsExtension) { - console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); - console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); - return; - } +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() - var nodeNativeEncodings = { - 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, - 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, - }; - - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } - - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; - - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); - - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } - - original.SlowBufferWrite = SlowBuffer.prototype.write; - SlowBuffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); - - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - } - - // -- Buffer --------------------------------------------------------------- - - original.BufferIsEncoding = Buffer.isEncoding; - Buffer.isEncoding = function(encoding) { - return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); - } - - original.BufferByteLength = Buffer.byteLength; - Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); - - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } - - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); - - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } - - original.BufferWrite = Buffer.prototype.write; - Buffer.prototype.write = function(string, offset, length, encoding) { - var _offset = offset, _length = length, _encoding = encoding; - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferWrite.call(this, string, _offset, _length, _encoding); - - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - - // TODO: Set _charsWritten. - } +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) +/** + * Get the code class of a status code. + * @private + */ - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} - original.ReadableSetEncoding = Readable.prototype.setEncoding; - Readable.prototype.setEncoding = function setEncoding(enc, options) { - // Use our own decoder, it has the same interface. - // We cannot use original function as it doesn't handle BOM-s. - this._readableState.decoder = iconv.getDecoder(enc, options); - this._readableState.encoding = enc; - } +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ - Readable.prototype.collect = iconv._collect; +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + if (arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + continue + } + switch (typeof arg) { + case 'string': + msg = arg + break + case 'number': + status = arg + if (i !== 0) { + deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') } + break + case 'object': + props = arg + break } + } - // Remove iconv-lite Node primitive extensions. - iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { - if (!iconv.supportsNodeEncodingsExtension) - return; - if (!original) - throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") - - delete Buffer.isNativeEncoding; - - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; + // constructor + var HttpError = createError[status] || createError[codeClass(status)] - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; - } + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } - original = undefined; + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] } -} - - -/***/ }), + } -/***/ 19032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return err +} -"use strict"; +/** + * Create HTTP error abstract base class. + * @private + */ +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } -// Some environments don't have global Buffer (e.g. React Native). -// Solution would be installing npm modules "buffer" and "stream" explicitly. -var Buffer = __nccwpck_require__(15118).Buffer; + inherits(HttpError, Error) -var bomHandling = __nccwpck_require__(67961), - iconv = module.exports; + return HttpError +} -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; +/** + * Create a constructor for a client error. + * @private + */ -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; +function createClientErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) - var encoder = iconv.getEncoder(encoding, options); + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; - } + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. - } + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) - var decoder = iconv.getDecoder(encoding, options); + return err + } - var res = decoder.write(buf); - var trail = decoder.end(); + inherits(ClientError, HttpError) + nameFunc(ClientError, className) - return trail ? (res + trail) : res; -} + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } + return ClientError } -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; - -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); +/** + * Create a constructor for a server error. + * @private + */ - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; +function createServerErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' - var codecDef = iconv.encodings[enc]; + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); + return err + } - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; + inherits(ServerError, HttpError) + nameFunc(ServerError, className) - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } - } -} + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); + return ServerError } -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); +/** + * Set the name of a function, if possible. + * @private + */ - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') - return encoder; + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } } -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); - - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); - - return decoder; -} +/** + * Populate the exports object with constructors for every error class. + * @private + */ +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) -// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. -var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; -if (nodeVer) { + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - __nccwpck_require__(76409)(iconv); + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError } + }) - // Load Node primitive extensions. - __nccwpck_require__(30393)(iconv); + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') } -if (false) {} - /***/ }), -/***/ 76409: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 15098: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var Buffer = __nccwpck_require__(64293).Buffer, - Transform = __nccwpck_require__(92413).Transform; - - -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } - - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } - - iconv.supportsStreams = true; - - - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; -}; - - -// == Encoder stream ======================================================= -function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); -} - -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); - -IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __importDefault(__nccwpck_require__(11631)); +const tls_1 = __importDefault(__nccwpck_require__(4016)); +const url_1 = __importDefault(__nccwpck_require__(78835)); +const assert_1 = __importDefault(__nccwpck_require__(42357)); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const agent_base_1 = __nccwpck_require__(49690); +const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595)); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; } - catch (e) { - done(e); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + const servername = opts.servername || opts.host; + if (!servername) { + throw new Error('Could not determine "servername"'); + } + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket(); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); } } - -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } +exports.default = HttpsProxyAgent; +function resume(socket) { + socket.resume(); } - -IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); } - - -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; } - -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); - -IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } } + return ret; } +//# sourceMappingURL=agent.js.map -IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} +/***/ }), -IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; -} +/***/ 77219: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(__nccwpck_require__(15098)); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 91230: -/***/ ((module) => { +/***/ 595: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -// A simple implementation of make-array -function makeArray (subject) { - return Array.isArray(subject) - ? subject - : [subject] +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); } +exports.default = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map -const EMPTY = '' -const SPACE = ' ' -const ESCAPE = '\\' -const REGEX_TEST_BLANK_LINE = /^\s+$/ -const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ -const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ -const REGEX_SPLITALL_CRLF = /\r?\n/g -// /foo, -// ./foo, -// ../foo, -// . -// .. -const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ +/***/ }), -const SLASH = '/' -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore' +/***/ 39695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const define = (object, key, value) => - Object.defineProperty(object, key, {value}) +"use strict"; -const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g +var Buffer = __nccwpck_require__(15118).Buffer; -// Sanitize the range of a regular expression -// The cases are complicated, see test cases for details -const sanitizeRange = range => range.replace( - REGEX_REGEXP_RANGE, - (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) - ? match - // Invalid range (out of order) which is ok for gitignore rules but - // fatal for JavaScript regular expression, so eliminate it. - : EMPTY -) +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. -// See fixtures #59 -const cleanRangeBackSlash = slashes => { - const {length} = slashes - return slashes.slice(0, length - length % 2) -} +exports._dbcs = DBCSCodec; -// > If the pattern ends with a slash, -// > it is removed for the purpose of the following description, -// > but it would only find a match with a directory. -// > In other words, foo/ will match a directory foo and paths underneath it, -// > but will not match a regular file or a symbolic link foo -// > (this is consistent with the way how pathspec works in general in Git). -// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' -// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call -// you could use option `mark: true` with `glob` +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; -// '`foo/`' should not continue with the '`..`' -const REPLACERS = [ +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? SPACE - : EMPTY - ], - // replace (\ ) with ' ' - [ - /\\\s/g, - () => SPACE - ], +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); - // Escape metacharacters - // which is written down by users but means special for regular expressions. + // Load tables. + var mappingTable = codecOptions.table(); - // > There are 12 characters with special meanings: - // > - the backslash \, - // > - the caret ^, - // > - the dollar sign $, - // > - the period or dot ., - // > - the vertical bar or pipe symbol |, - // > - the question mark ?, - // > - the asterisk or star *, - // > - the plus sign +, - // > - the opening parenthesis (, - // > - the closing parenthesis ), - // > - and the opening square bracket [, - // > - the opening curly brace {, - // > These special characters are often called "metacharacters". - [ - /[\\$.|*+(){^]/g, - match => `\\${match}` - ], - [ - // > a question mark (?) matches a single character - /(?!\\)\?/g, - () => '[^/]' - ], + // Decode tables: MBCS -> Unicode. - // leading slash - [ + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. - // > A leading slash matches the beginning of the pathname. - // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". - // A leading slash matches the beginning of the pathname - /^\//, - () => '^' - ], + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); - [ - // > A leading "**" followed by a slash means match in all directories. - // > For example, "**/foo" matches file or directory "foo" anywhere, - // > the same as pattern "foo". - // > "**/foo/bar" matches file or directory "bar" anywhere that is directly - // > under directory "foo". - // Notice that the '*'s have been replaced as '\\*' - /^\^*\\\*\\\*\\\//, + this.defaultCharUnicode = iconv.defaultCharUnicode; - // '**/foo' <-> 'foo' - () => '^(?:.*\\/)?' - ], + + // Encode tables: Unicode -> DBCS. - // starting - [ - // there will be no leading '/' - // (which has been replaced by section "leading slash") - // If starts with '**', adding a '^' to the regular expression also works - /^(?=[^^])/, - function startingReplacer () { - // If has a slash `/` at the beginning or middle - return !/\/(?!$)/.test(this) - // > Prior to 2.22.1 - // > If the pattern does not contain a slash /, - // > Git treats it as a shell glob pattern - // Actually, if there is only a trailing slash, - // git also treats it as a shell glob pattern + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; - // After 2.22.1 (compatible but clearer) - // > If there is a separator at the beginning or middle (or both) - // > of the pattern, then the pattern is relative to the directory - // > level of the particular .gitignore file itself. - // > Otherwise the pattern may also match at any level below - // > the .gitignore level. - ? '(?:^|\\/)' + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } - ], - - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, - - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer - // Check if it is not the last `'/**'` - (_, index, str) => index + 6 < str.length + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); - // case: /**/ - // > A slash followed by two consecutive asterisks then a slash matches - // > zero or more directories. - // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. - // '/**/' - ? '(?:\\/[^\\/]+)*' - // case: /** - // > A trailing `"/**"` matches everything inside. + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. - // #21: everything inside but it should not include the current folder - : '\\/.+' - ], + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); - // intermediate wildcards - [ - // Never replace escaped '*' - // ignore rule '\*' will match the path '*' + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} - // '*.js' matches '.js' - // '*.js' doesn't match 'abc' - (_, p1) => `${p1}[^\\/]*` - ], +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; - [ - // unescape, revert step 3 except for back slash - // For example, if a user escape a '\\*', - // after step 3, the result will be '\\\\\\*' - /\\\\\\(?=[$.|*+(){^])/g, - () => ESCAPE - ], +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); - [ - // '\\\\' -> '\\' - /\\\\/g, - () => ESCAPE - ], + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; - [ - // > The range notation, e.g. [a-zA-Z], - // > can be used to match one of the characters in a range. + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} - // `\` is escaped by step 3 - /(\\)?\[([^\]/]*?)(\\*)($|\])/g, - (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE - // '\\[bar]' -> '\\\\[bar\\]' - ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` - : close === ']' - ? endEscape.length % 2 === 0 - // A normal case, and it is a range notation - // '[bar]' - // '[bar\\\\]' - ? `[${sanitizeRange(range)}${endEscape}]` - // Invalid range notaton - // '[bar\\]' -> '[bar\\\\]' - : '[]' - : '[]' - ], - // ending - [ - // 'js' will not match 'js.' - // 'ab' will not match 'abc' - /(?:[^*])$/, +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); - // WTF! - // https://git-scm.com/docs/gitignore - // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) - // which re-fixes #24, #38 + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; - // > If there is a separator at the end of the pattern then the pattern - // > will only match directories, otherwise the pattern can match both - // > files and directories. + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. - // 'js*' will not match 'a.js' - // 'js/' will not match 'a.js' - // 'js' will match 'a.js' and 'a.js/' - match => /\/$/.test(match) - // foo/ will not match 'foo' - ? `${match}$` - // foo matches 'foo' and 'foo/' - : `${match}(?=$|\\/$)` - ], + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (_, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match EMPTY - // '/*' does not match everything +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*' +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; - return `${prefix}(?=$|\\/$)` + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); } - ], -] - -// A simple cache, because an ignore rule only has only one certain meaning -const regexCache = Object.create(null) -// @param {pattern} -const makeRegex = (pattern, negative, ignorecase) => { - const r = regexCache[pattern] - if (r) { - return r - } + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } - // const replacers = negative - // ? NEGATIVE_REPLACERS - // : POSITIVE_REPLACERS + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} - const source = REPLACERS.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ) +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; - return regexCache[pattern] = ignorecase - ? new RegExp(source, 'i') - : new RegExp(source) + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } } -const isString = subject => typeof subject === 'string' - -// > A blank line matches no files, so it can serve as a separator for readability. -const checkPattern = pattern => pattern - && isString(pattern) - && !REGEX_TEST_BLANK_LINE.test(pattern) - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0 -const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) +// == Encoder ================================================================== -class IgnoreRule { - constructor ( - origin, - pattern, - negative, - regex - ) { - this.origin = origin - this.pattern = pattern - this.negative = negative - this.regex = regex - } +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; } -const createRule = (pattern, ignorecase) => { - const origin = pattern - let negative = false +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true - pattern = pattern.substr(1) - } + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } - pattern = pattern - // > Put a backslash ("\") in front of the first "!" for patterns that - // > begin with a literal "!", for example, `"\!important!.txt"`. - .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') - // > Put a backslash ("\") in front of the first hash for patterns that - // > begin with a hash. - .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } - const regex = makeRegex(pattern, negative, ignorecase) + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; - return new IgnoreRule( - origin, - pattern, - negative, - regex - ) -} + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; -const throwError = (message, Ctor) => { - throw new Ctor(message) -} + } else if (resCode == undefined) { // Current character is not part of the sequence. -const checkPath = (path, originalPath, doThrow) => { - if (!isString(path)) { - return doThrow( - `path must be a string, but got \`${originalPath}\``, - TypeError - ) - } + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. - // We don't know if we should ignore EMPTY, so throw - if (!path) { - return doThrow(`path must not be empty`, TypeError) - } + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } - // Check if it is a relative path - if (checkPath.isNotRelative(path)) { - const r = '`path.relative()`d' - return doThrow( - `path should be a ${r} string, but got "${originalPath}"`, - RangeError - ) - } + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } - return true + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); } -const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. -checkPath.isNotRelative = isNotRelative -checkPath.convert = p => p + var newBuf = Buffer.alloc(10), j = 0; -class Ignore { - constructor ({ - ignorecase = true - } = {}) { - this._rules = [] - this._ignorecase = ignorecase - define(this, KEY_IGNORE, true) - this._initCache() - } - - _initCache () { - this._ignoreCache = Object.create(null) - this._testCache = Object.create(null) - } - - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules) - this._added = true - return + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; } - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignorecase) - this._added = true - this._rules.push(rule) + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; } - } - - // @param {Array | string | Ignore} pattern - add (pattern) { - this._added = false + + return newBuf.slice(0, j); +} - makeArray( - isString(pattern) - ? splitPattern(pattern) - : pattern - ).forEach(this._addPattern, this) +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache() - } - return this - } +// == Decoder ================================================================== - // legacy - addPattern (pattern) { - return this.add(pattern) - } +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); - // | ignored : unignored - // negative | 0:0 | 0:1 | 1:0 | 1:1 - // -------- | ------- | ------- | ------- | -------- - // 0 | TEST | TEST | SKIP | X - // 1 | TESTIF | SKIP | TEST | X + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} - // - SKIP: always skip - // - TEST: always test - // - TESTIF: only test if checkUnignored - // - X: that never happen +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; - // @param {boolean} whether should check if the path is unignored, - // setting `checkUnignored` to `false` could reduce additional - // path matching. + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; - // @returns {TestResult} true if a file is ignored - _testOne (path, checkUnignored) { - let ignored = false - let unignored = false + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; - this._rules.forEach(rule => { - const {negative} = rule - if ( - unignored === negative && ignored !== unignored - || negative && !ignored && !unignored && !checkUnignored - ) { - return - } + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); - const matched = rule.regex.test(path) + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; - if (matched) { - ignored = !negative - unignored = negative - } - }) + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; - return { - ignored, - unignored + // Reset trie node. + nodeIdx = 0; seqStart = i+1; } - } - // @returns {TestResult} - _test (originalPath, cache, checkUnignored, slices) { - const path = originalPath - // Supports nullable path - && checkPath.convert(originalPath) + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} - checkPath(path, originalPath, throwError) +DBCSDecoder.prototype.end = function() { + var ret = ''; - return this._t(path, cache, checkUnignored, slices) - } + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); - _t (path, cache, checkUnignored, slices) { - if (path in cache) { - return cache[path] + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); } - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH) - } + this.nodeIdx = 0; + return ret; +} - slices.pop() +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; - // If the path has no parent directory, just test it - if (!slices.length) { - return cache[path] = this._testOne(path, checkUnignored) + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; } + return l; +} - const parent = this._t( - slices.join(SLASH) + SLASH, - cache, - checkUnignored, - slices - ) - // If the path contains a parent directory, check the parent first - return cache[path] = parent.ignored - // > It is not possible to re-include a file if a parent directory of - // > that file is excluded. - ? parent - : this._testOne(path, checkUnignored) - } - ignores (path) { - return this._test(path, this._ignoreCache, false).ignored - } +/***/ }), - createFilter () { - return path => !this.ignores(path) - } +/***/ 91386: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - filter (paths) { - return makeArray(paths).filter(this.createFilter()) - } +"use strict"; - // @returns {TestResult} - test (path) { - return this._test(path, this._testCache, true) - } -} -const factory = options => new Ignore(options) +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. -const returnFalse = () => false +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) -const isPathValid = path => - checkPath(path && checkPath.convert(path), path, returnFalse) + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html -factory.isPathValid = isPathValid + 'shiftjis': { + type: '_dbcs', + table: function() { return __nccwpck_require__(64108) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', -// Fixes typescript -factory.default = factory + 'eucjp': { + type: '_dbcs', + table: function() { return __nccwpck_require__(72417) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, -module.exports = factory + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. -// Windows -// -------------------------------------------------------------- -/* istanbul ignore if */ -if ( - // Detect `process` so that it can run in browsers. - typeof process !== 'undefined' - && ( - process.env && process.env.IGNORE_TEST_WIN32 - || process.platform === 'win32' - ) -) { - /* eslint no-control-regex: "off" */ - const makePosix = str => /^\\\\\?\\/.test(str) - || /["<>|\u0000-\u001F]+/u.test(str) - ? str - : str.replace(/\\/g, '/') - checkPath.convert = makePosix + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' - // 'd:\\foo' - const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i - checkPath.isNotRelative = path => - REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) - || isNotRelative(path) -} + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return __nccwpck_require__(97803) }, + }, -/***/ }), + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', -/***/ 98043: -/***/ ((module) => { + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, + gb18030: function() { return __nccwpck_require__(86351) }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, -"use strict"; + 'chinese': 'gb18030', -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return __nccwpck_require__(87013) }, + }, - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. - if (count === 0) { - return string; - } + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return __nccwpck_require__(33104) }, + }, - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return __nccwpck_require__(33104).concat(__nccwpck_require__(43612)) }, + encodeSkipVals: [0xa2cc], + }, - return string.replace(regex, options.indent.repeat(count)); + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', }; /***/ }), -/***/ 44124: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 82733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -try { - var util = __nccwpck_require__(31669); - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = __nccwpck_require__(8544); +"use strict"; + + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + __nccwpck_require__(12376), + __nccwpck_require__(11155), + __nccwpck_require__(51644), + __nccwpck_require__(26657), + __nccwpck_require__(41080), + __nccwpck_require__(21012), + __nccwpck_require__(39695), + __nccwpck_require__(91386), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; } /***/ }), -/***/ 8544: -/***/ ((module) => { +/***/ 12376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} +"use strict"; +var Buffer = __nccwpck_require__(15118).Buffer; -/***/ }), +// Export Node.js internal encodings. -/***/ 30545: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", -"use strict"; + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(90803); -const utils_1 = __nccwpck_require__(94832); -const RedisParser = __nccwpck_require__(53315); -const SubscriptionSet_1 = __nccwpck_require__(73527); -const debug = utils_1.Debug("dataHandler"); -class DataHandler { - constructor(redis, parserOptions) { - this.redis = redis; - const parser = new RedisParser({ - stringNumbers: parserOptions.stringNumbers, - returnBuffers: !parserOptions.dropBufferSupport, - returnError: (err) => { - this.returnError(err); - }, - returnFatalError: (err) => { - this.returnFatalError(err); - }, - returnReply: (reply) => { - this.returnReply(reply); - }, - }); - redis.stream.on("data", (data) => { - parser.execute(data); - }); - } - returnFatalError(err) { - err.message += ". Please report this."; - this.redis.recoverFromFatalError(err, err, { offlineQueue: false }); - } - returnError(err) { - const item = this.shiftCommand(err); - if (!item) { - return; + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; } - err.command = { - name: item.command.name, - args: item.command.args, - }; - this.redis.handleReconnection(err, item); } - returnReply(reply) { - if (this.handleMonitorReply(reply)) { - return; - } - if (this.handleSubscriberReply(reply)) { - return; - } - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", item.command.name)) { - this.redis.condition.subscriber = new SubscriptionSet_1.default(); - this.redis.condition.subscriber.add(item.command.name, reply[1].toString()); - if (!fillSubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } - } - else if (command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", item.command.name)) { - if (!fillUnsubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = __nccwpck_require__(24304).StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); +} + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return Buffer.from(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); } - else { - item.command.resolve(reply); + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); } } - handleSubscriberReply(reply) { - if (!this.redis.condition.subscriber) { - return false; - } - const replyType = Array.isArray(reply) ? reply[0].toString() : null; - debug('receive reply "%s" in subscriber mode', replyType); - switch (replyType) { - case "message": - if (this.redis.listeners("message").length > 0) { - // Check if there're listeners to avoid unnecessary `toString()`. - this.redis.emit("message", reply[1].toString(), reply[2].toString()); - } - this.redis.emit("messageBuffer", reply[1], reply[2]); - break; - case "pmessage": { - const pattern = reply[1].toString(); - if (this.redis.listeners("pmessage").length > 0) { - this.redis.emit("pmessage", pattern, reply[2].toString(), reply[3].toString()); - } - this.redis.emit("pmessageBuffer", pattern, reply[2], reply[3]); - break; - } - case "subscribe": - case "psubscribe": { - const channel = reply[1].toString(); - this.redis.condition.subscriber.add(replyType, channel); - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (!fillSubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } - break; + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; } - case "unsubscribe": - case "punsubscribe": { - const channel = reply[1] ? reply[1].toString() : null; - if (channel) { - this.redis.condition.subscriber.del(replyType, channel); - } - const count = reply[2]; - if (count === 0) { - this.redis.condition.subscriber = false; - } - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (!fillUnsubCommand(item.command, count)) { - this.redis.commandQueue.unshift(item); - } - break; + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; } - default: { - const item = this.shiftCommand(reply); - if (!item) { - return; + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); } - item.command.resolve(reply); + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; } } - return true; - } - handleMonitorReply(reply) { - if (this.redis.status !== "monitoring") { - return false; - } - const replyStr = reply.toString(); - if (replyStr === "OK") { - // Valid commands in the monitoring mode are AUTH and MONITOR, - // both of which always reply with 'OK'. - // So if we got an 'OK', we can make certain that - // the reply is made to AUTH & MONITO. - return false; - } - // Since commands sent in the monitoring mode will trigger an exception, - // any replies we received in the monitoring mode should consider to be - // realtime monitor data instead of result of commands. - const len = replyStr.indexOf(" "); - const timestamp = replyStr.slice(0, len); - const argindex = replyStr.indexOf('"'); - const args = replyStr - .slice(argindex + 1, -1) - .split('" "') - .map((elem) => elem.replace(/\\"/g, '"')); - const dbAndSource = replyStr.slice(len + 2, argindex - 2).split(" "); - this.redis.emit("monitor", timestamp, args, dbAndSource[1], dbAndSource[0]); - return true; - } - shiftCommand(reply) { - const item = this.redis.commandQueue.shift(); - if (!item) { - const message = "Command queue state error. If you can reproduce this, please report it."; - const error = new Error(message + - (reply instanceof Error - ? ` Last error: ${reply.message}` - : ` Last reply: ${reply.toString()}`)); - this.redis.emit("error", error); - return null; - } - return item; - } -} -exports.default = DataHandler; -function fillSubCommand(command, count) { - // TODO: use WeakMap here - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; - } - return false; + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; } -function fillUnsubCommand(command, count) { - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; - } - if (command.remainReplies === 0) { - if (count === 0) { - command.resolve(count); - return true; - } - return false; - } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; - } - return false; + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; } /***/ }), -/***/ 6134: +/***/ 26657: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(92413); -/** - * Convenient class to convert the process of scaning keys to a readable stream. - * - * @export - * @class ScanStream - * @extends {Readable} - */ -class ScanStream extends stream_1.Readable { - constructor(opt) { - super(opt); - this.opt = opt; - this._redisCursor = "0"; - this._redisDrained = false; - } - _read() { - if (this._redisDrained) { - this.push(null); - return; - } - const args = [this._redisCursor]; - if (this.opt.key) { - args.unshift(this.opt.key); - } - if (this.opt.match) { - args.push("MATCH", this.opt.match); - } - if (this.opt.count) { - args.push("COUNT", String(this.opt.count)); - } - this.opt.redis[this.opt.command](args, (err, res) => { - if (err) { - this.emit("error", err); - return; - } - this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0]; - if (this._redisCursor === "0") { - this._redisDrained = true; - } - this.push(res[1]); - }); - } - close() { - this._redisDrained = true; - } -} -exports.default = ScanStream; +var Buffer = __nccwpck_require__(15118).Buffer; +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). -/***/ }), +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } -/***/ 73527: -/***/ ((__unused_webpack_module, exports) => { + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); -"use strict"; + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Tiny class to simplify dealing with subscription set - * - * @export - * @class SubscriptionSet - */ -class SubscriptionSet { - constructor() { - this.set = { - subscribe: {}, - psubscribe: {}, - }; - } - add(set, channel) { - this.set[mapSet(set)][channel] = true; - } - del(set, channel) { - delete this.set[mapSet(set)][channel]; - } - channels(set) { - return Object.keys(this.set[mapSet(set)]); - } - isEmpty() { - return (this.channels("subscribe").length === 0 && - this.channels("psubscribe").length === 0); - } + this.encodeBuf = encodeBuf; } -exports.default = SubscriptionSet; -function mapSet(set) { - if (set === "unsubscribe") { - return "subscribe"; - } - if (set === "punsubscribe") { - return "psubscribe"; - } - return set; + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; } +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} -/***/ }), +SBCSEncoder.prototype.end = function() { +} -/***/ 97873: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -const PromiseContainer = __nccwpck_require__(71475); -const calculateSlot = __nccwpck_require__(48481); -const standard_as_callback_1 = __nccwpck_require__(91543); -exports.kExec = Symbol("exec"); -exports.kCallbacks = Symbol("callbacks"); -exports.notAllowedAutoPipelineCommands = [ - "auth", - "info", - "script", - "quit", - "cluster", - "pipeline", - "multi", - "subscribe", - "psubscribe", - "unsubscribe", - "unpsubscribe", -]; -function findAutoPipeline(client, _commandName, ...args) { - if (!client.isCluster) { - return "main"; - } - // We have slot information, we can improve routing by grouping slots served by the same subset of nodes - return client.slots[calculateSlot(args[0])].join(","); -} -function executeAutoPipeline(client, slotKey) { - /* - If a pipeline is already executing, keep queueing up commands - since ioredis won't serve two pipelines at the same time - */ - if (client._runningAutoPipelines.has(slotKey)) { - return; - } - client._runningAutoPipelines.add(slotKey); - // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline - const pipeline = client._autoPipelines.get(slotKey); - client._autoPipelines.delete(slotKey); - const callbacks = pipeline[exports.kCallbacks]; - // Perform the call - pipeline.exec(function (err, results) { - client._runningAutoPipelines.delete(slotKey); - /* - Invoke all callback in nextTick so the stack is cleared - and callbacks can throw errors without affecting other callbacks. - */ - if (err) { - for (let i = 0; i < callbacks.length; i++) { - process.nextTick(callbacks[i], err); - } - } - else { - for (let i = 0; i < callbacks.length; i++) { - process.nextTick(callbacks[i], ...results[i]); - } - } - // If there is another pipeline on the same node, immediately execute it without waiting for nextTick - if (client._autoPipelines.has(slotKey)) { - executeAutoPipeline(client, slotKey); - } - }); -} -function shouldUseAutoPipelining(client, commandName) { - return (client.options.enableAutoPipelining && - !client.isPipeline && - !exports.notAllowedAutoPipelineCommands.includes(commandName) && - !client.options.autoPipeliningIgnoredCommands.includes(commandName)); -} -exports.shouldUseAutoPipelining = shouldUseAutoPipelining; -function executeWithAutoPipelining(client, commandName, args, callback) { - const CustomPromise = PromiseContainer.get(); - // On cluster mode let's wait for slots to be available - if (client.isCluster && !client.slots.length) { - return new CustomPromise(function (resolve, reject) { - client.delayUntilReady((err) => { - if (err) { - reject(err); - return; - } - executeWithAutoPipelining(client, commandName, args, callback).then(resolve, reject); - }); - }); - } - const slotKey = findAutoPipeline(client, commandName, ...args); - if (!client._autoPipelines.has(slotKey)) { - const pipeline = client.pipeline(); - pipeline[exports.kExec] = false; - pipeline[exports.kCallbacks] = []; - client._autoPipelines.set(slotKey, pipeline); - } - const pipeline = client._autoPipelines.get(slotKey); - /* - Mark the pipeline as scheduled. - The symbol will make sure that the pipeline is only scheduled once per tick. - New commands are appended to an already scheduled pipeline. - */ - if (!pipeline[exports.kExec]) { - pipeline[exports.kExec] = true; - /* - Deferring with setImmediate so we have a chance to capture multiple - commands that can be scheduled by I/O events already in the event loop queue. - */ - setImmediate(executeAutoPipeline, client, slotKey); - } - // Create the promise which will execute the - const autoPipelinePromise = new CustomPromise(function (resolve, reject) { - pipeline[exports.kCallbacks].push(function (err, value) { - if (err) { - reject(err); - return; - } - resolve(value); - }); - pipeline[commandName](...args); - }); - return standard_as_callback_1.default(autoPipelinePromise, callback); -} -exports.executeWithAutoPipelining = executeWithAutoPipelining; - - -/***/ }), - -/***/ 35835: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const dns_1 = __nccwpck_require__(40881); -exports.DEFAULT_CLUSTER_OPTIONS = { - clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000), - enableOfflineQueue: true, - enableReadyCheck: true, - scaleReads: "master", - maxRedirections: 16, - retryDelayOnFailover: 100, - retryDelayOnClusterDown: 100, - retryDelayOnTryAgain: 100, - slotsRefreshTimeout: 1000, - slotsRefreshInterval: 5000, - dnsLookup: dns_1.lookup, - enableAutoPipelining: false, - autoPipeliningIgnoredCommands: [], - maxScriptsCachingTime: 60000, -}; - - -/***/ }), - -/***/ 18394: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(94582); -const utils_1 = __nccwpck_require__(94832); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("cluster:subscriber"); -const SUBSCRIBER_CONNECTION_NAME = "ioredisClusterSubscriber"; -class ClusterSubscriber { - constructor(connectionPool, emitter) { - this.connectionPool = connectionPool; - this.emitter = emitter; - this.started = false; - this.subscriber = null; - this.connectionPool.on("-node", (_, key) => { - if (!this.started || !this.subscriber) { - return; - } - if (util_1.getNodeKey(this.subscriber.options) === key) { - debug("subscriber has left, selecting a new one..."); - this.selectSubscriber(); - } - }); - this.connectionPool.on("+node", () => { - if (!this.started || this.subscriber) { - return; - } - debug("a new node is discovered and there is no subscriber, selecting a new one..."); - this.selectSubscriber(); - }); - } - getInstance() { - return this.subscriber; - } - selectSubscriber() { - const lastActiveSubscriber = this.lastActiveSubscriber; - // Disconnect the previous subscriber even if there - // will not be a new one. - if (lastActiveSubscriber) { - lastActiveSubscriber.disconnect(); - } - const sampleNode = utils_1.sample(this.connectionPool.getNodes()); - if (!sampleNode) { - debug("selecting subscriber failed since there is no node discovered in the cluster yet"); - this.subscriber = null; - return; - } - const { options } = sampleNode; - debug("selected a subscriber %s:%s", options.host, options.port); - /* - * Create a specialized Redis connection for the subscription. - * Note that auto reconnection is enabled here. - * - * `enableReadyCheck` is also enabled because although subscription is allowed - * while redis is loading data from the disk, we can check if the password - * provided for the subscriber is correct, and if not, the current subscriber - * will be disconnected and a new subscriber will be selected. - */ - this.subscriber = new redis_1.default({ - port: options.port, - host: options.host, - username: options.username, - password: options.password, - enableReadyCheck: true, - connectionName: SUBSCRIBER_CONNECTION_NAME, - lazyConnect: true, - tls: options.tls, - }); - // Ignore the errors since they're handled in the connection pool. - this.subscriber.on("error", utils_1.noop); - // Re-subscribe previous channels - const previousChannels = { subscribe: [], psubscribe: [] }; - if (lastActiveSubscriber) { - const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition; - if (condition && condition.subscriber) { - previousChannels.subscribe = condition.subscriber.channels("subscribe"); - previousChannels.psubscribe = condition.subscriber.channels("psubscribe"); - } - } - if (previousChannels.subscribe.length || - previousChannels.psubscribe.length) { - let pending = 0; - for (const type of ["subscribe", "psubscribe"]) { - const channels = previousChannels[type]; - if (channels.length) { - pending += 1; - debug("%s %d channels", type, channels.length); - this.subscriber[type](channels) - .then(() => { - if (!--pending) { - this.lastActiveSubscriber = this.subscriber; - } - }) - .catch(utils_1.noop); - } - } - } - else { - this.lastActiveSubscriber = this.subscriber; - } - for (const event of ["message", "messageBuffer"]) { - this.subscriber.on(event, (arg1, arg2) => { - this.emitter.emit(event, arg1, arg2); - }); - } - for (const event of ["pmessage", "pmessageBuffer"]) { - this.subscriber.on(event, (arg1, arg2, arg3) => { - this.emitter.emit(event, arg1, arg2, arg3); - }); - } - } - start() { - this.started = true; - this.selectSubscriber(); - debug("started"); - } - stop() { - this.started = false; - if (this.subscriber) { - this.subscriber.disconnect(); - this.subscriber = null; - } - debug("stopped"); +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; } + return newBuf.toString('ucs2'); } -exports.default = ClusterSubscriber; - - -/***/ }), -/***/ 34589: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const events_1 = __nccwpck_require__(28614); -const utils_1 = __nccwpck_require__(94832); -const util_1 = __nccwpck_require__(94582); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("cluster:connectionPool"); -class ConnectionPool extends events_1.EventEmitter { - constructor(redisOptions) { - super(); - this.redisOptions = redisOptions; - // master + slave = all - this.nodes = { - all: {}, - master: {}, - slave: {}, - }; - this.specifiedOptions = {}; - } - getNodes(role = "all") { - const nodes = this.nodes[role]; - return Object.keys(nodes).map((key) => nodes[key]); - } - getInstanceByKey(key) { - return this.nodes.all[key]; - } - getSampleInstance(role) { - const keys = Object.keys(this.nodes[role]); - const sampleKey = utils_1.sample(keys); - return this.nodes[role][sampleKey]; - } - /** - * Find or create a connection to the node - * - * @param {IRedisOptions} node - * @param {boolean} [readOnly=false] - * @returns {*} - * @memberof ConnectionPool - */ - findOrCreate(node, readOnly = false) { - const key = util_1.getNodeKey(node); - readOnly = Boolean(readOnly); - if (this.specifiedOptions[key]) { - Object.assign(node, this.specifiedOptions[key]); - } - else { - this.specifiedOptions[key] = node; - } - let redis; - if (this.nodes.all[key]) { - redis = this.nodes.all[key]; - if (redis.options.readOnly !== readOnly) { - redis.options.readOnly = readOnly; - debug("Change role of %s to %s", key, readOnly ? "slave" : "master"); - redis[readOnly ? "readonly" : "readwrite"]().catch(utils_1.noop); - if (readOnly) { - delete this.nodes.master[key]; - this.nodes.slave[key] = redis; - } - else { - delete this.nodes.slave[key]; - this.nodes.master[key] = redis; - } - } - } - else { - debug("Connecting to %s as %s", key, readOnly ? "slave" : "master"); - redis = new redis_1.default(utils_1.defaults({ - // Never try to reconnect when a node is lose, - // instead, waiting for a `MOVED` error and - // fetch the slots again. - retryStrategy: null, - // Offline queue should be enabled so that - // we don't need to wait for the `ready` event - // before sending commands to the node. - enableOfflineQueue: true, - readOnly: readOnly, - }, node, this.redisOptions, { lazyConnect: true })); - this.nodes.all[key] = redis; - this.nodes[readOnly ? "slave" : "master"][key] = redis; - redis.once("end", () => { - this.removeNode(key); - this.emit("-node", redis, key); - if (!Object.keys(this.nodes.all).length) { - this.emit("drain"); - } - }); - this.emit("+node", redis, key); - redis.on("error", function (error) { - this.emit("nodeError", error, key); - }); - } - return redis; - } - /** - * Remove a node from the pool. - */ - removeNode(key) { - const { nodes } = this; - if (nodes.all[key]) { - debug("Remove %s from the pool", key); - delete nodes.all[key]; - } - delete nodes.master[key]; - delete nodes.slave[key]; - } - /** - * Reset the pool with a set of nodes. - * The old node will be removed. - * - * @param {(Array)} nodes - * @memberof ConnectionPool - */ - reset(nodes) { - debug("Reset with %O", nodes); - const newNodes = {}; - nodes.forEach((node) => { - const key = util_1.getNodeKey(node); - // Don't override the existing (master) node - // when the current one is slave. - if (!(node.readOnly && newNodes[key])) { - newNodes[key] = node; - } - }); - Object.keys(this.nodes.all).forEach((key) => { - if (!newNodes[key]) { - debug("Disconnect %s because the node does not hold any slot", key); - this.nodes.all[key].disconnect(); - this.removeNode(key); - } - }); - Object.keys(newNodes).forEach((key) => { - const node = newNodes[key]; - this.findOrCreate(node, node.readOnly); - }); - } +SBCSDecoder.prototype.end = function() { } -exports.default = ConnectionPool; /***/ }), -/***/ 12770: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 21012: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const Deque = __nccwpck_require__(42342); -const debug = utils_1.Debug("delayqueue"); -/** - * Queue that runs items after specified duration - * - * @export - * @class DelayQueue - */ -class DelayQueue { - constructor() { - this.queues = {}; - this.timeouts = {}; - } - /** - * Add a new item to the queue - * - * @param {string} bucket bucket name - * @param {Function} item function that will run later - * @param {IDelayQueueOptions} options - * @memberof DelayQueue - */ - push(bucket, item, options) { - const callback = options.callback || process.nextTick; - if (!this.queues[bucket]) { - this.queues[bucket] = new Deque(); - } - const queue = this.queues[bucket]; - queue.push(item); - if (!this.timeouts[bucket]) { - this.timeouts[bucket] = setTimeout(() => { - callback(() => { - this.timeouts[bucket] = null; - this.execute(bucket); - }); - }, options.timeout); - } - } - execute(bucket) { - const queue = this.queues[bucket]; - if (!queue) { - return; - } - const { length } = queue; - if (!length) { - return; - } - debug("send %d commands in %s queue", length, bucket); - this.queues[bucket] = null; - while (queue.length > 0) { - queue.shift()(); - } - } -} -exports.default = DelayQueue; - - -/***/ }), - -/***/ 17208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const events_1 = __nccwpck_require__(28614); -const ClusterAllFailedError_1 = __nccwpck_require__(97282); -const utils_1 = __nccwpck_require__(94832); -const ConnectionPool_1 = __nccwpck_require__(34589); -const util_1 = __nccwpck_require__(94582); -const ClusterSubscriber_1 = __nccwpck_require__(18394); -const DelayQueue_1 = __nccwpck_require__(12770); -const ScanStream_1 = __nccwpck_require__(6134); -const redis_errors_1 = __nccwpck_require__(81879); -const standard_as_callback_1 = __nccwpck_require__(91543); -const PromiseContainer = __nccwpck_require__(71475); -const ClusterOptions_1 = __nccwpck_require__(35835); -const utils_2 = __nccwpck_require__(94832); -const commands = __nccwpck_require__(98020); -const command_1 = __nccwpck_require__(90803); -const redis_1 = __nccwpck_require__(83609); -const commander_1 = __nccwpck_require__(33642); -const Deque = __nccwpck_require__(42342); -const debug = utils_1.Debug("cluster"); -/** - * Client for the official Redis Cluster - * - * @class Cluster - * @extends {EventEmitter} - */ -class Cluster extends events_1.EventEmitter { - /** - * Creates an instance of Cluster. - * - * @param {((string | number | object)[])} startupNodes - * @param {IClusterOptions} [options={}] - * @memberof Cluster - */ - constructor(startupNodes, options = {}) { - super(); - this.slots = []; - this.retryAttempts = 0; - this.delayQueue = new DelayQueue_1.default(); - this.offlineQueue = new Deque(); - this.isRefreshing = false; - this.isCluster = true; - this._autoPipelines = new Map(); - this._runningAutoPipelines = new Set(); - this._readyDelayedCallbacks = []; - this._addedScriptHashes = {}; - /** - * Every time Cluster#connect() is called, this value will be - * auto-incrementing. The purpose of this value is used for - * discarding previous connect attampts when creating a new - * connection. - * - * @private - * @type {number} - * @memberof Cluster - */ - this.connectionEpoch = 0; - commander_1.default.call(this); - this.startupNodes = startupNodes; - this.options = utils_1.defaults({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options); - // validate options - if (typeof this.options.scaleReads !== "function" && - ["all", "master", "slave"].indexOf(this.options.scaleReads) === -1) { - throw new Error('Invalid option scaleReads "' + - this.options.scaleReads + - '". Expected "all", "master", "slave" or a custom function'); - } - this.connectionPool = new ConnectionPool_1.default(this.options.redisOptions); - this.connectionPool.on("-node", (redis, key) => { - this.emit("-node", redis); - }); - this.connectionPool.on("+node", (redis) => { - this.emit("+node", redis); - }); - this.connectionPool.on("drain", () => { - this.setStatus("close"); - }); - this.connectionPool.on("nodeError", (error, key) => { - this.emit("node error", error, key); - }); - this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this); - if (this.options.lazyConnect) { - this.setStatus("wait"); - } - else { - this.connect().catch((err) => { - debug("connecting failed: %s", err); - }); - } - } - resetOfflineQueue() { - this.offlineQueue = new Deque(); - } - clearNodesRefreshInterval() { - if (this.slotsTimer) { - clearTimeout(this.slotsTimer); - this.slotsTimer = null; - } - } - resetNodesRefreshInterval() { - if (this.slotsTimer) { - return; - } - const nextRound = () => { - this.slotsTimer = setTimeout(() => { - debug('refreshing slot caches... (triggered by "slotsRefreshInterval" option)'); - this.refreshSlotsCache(() => { - nextRound(); - }); - }, this.options.slotsRefreshInterval); - }; - nextRound(); - } - /** - * Connect to a cluster - * - * @returns {Promise} - * @memberof Cluster - */ - connect() { - const Promise = PromiseContainer.get(); - return new Promise((resolve, reject) => { - if (this.status === "connecting" || - this.status === "connect" || - this.status === "ready") { - reject(new Error("Redis is already connecting/connected")); - return; - } - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = setInterval(() => { - this._addedScriptHashes = {}; - }, this.options.maxScriptsCachingTime); - const epoch = ++this.connectionEpoch; - this.setStatus("connecting"); - this.resolveStartupNodeHostnames() - .then((nodes) => { - if (this.connectionEpoch !== epoch) { - debug("discard connecting after resolving startup nodes because epoch not match: %d != %d", epoch, this.connectionEpoch); - reject(new redis_errors_1.RedisError("Connection is discarded because a new connection is made")); - return; - } - if (this.status !== "connecting") { - debug("discard connecting after resolving startup nodes because the status changed to %s", this.status); - reject(new redis_errors_1.RedisError("Connection is aborted")); - return; - } - this.connectionPool.reset(nodes); - function readyHandler() { - this.setStatus("ready"); - this.retryAttempts = 0; - this.executeOfflineCommands(); - this.resetNodesRefreshInterval(); - resolve(); - } - let closeListener = undefined; - const refreshListener = () => { - this.invokeReadyDelayedCallbacks(undefined); - this.removeListener("close", closeListener); - this.manuallyClosing = false; - this.setStatus("connect"); - if (this.options.enableReadyCheck) { - this.readyCheck((err, fail) => { - if (err || fail) { - debug("Ready check failed (%s). Reconnecting...", err || fail); - if (this.status === "connect") { - this.disconnect(true); - } - } - else { - readyHandler.call(this); - } - }); - } - else { - readyHandler.call(this); - } - }; - closeListener = function () { - const error = new Error("None of startup nodes is available"); - this.removeListener("refresh", refreshListener); - this.invokeReadyDelayedCallbacks(error); - reject(error); - }; - this.once("refresh", refreshListener); - this.once("close", closeListener); - this.once("close", this.handleCloseEvent.bind(this)); - this.refreshSlotsCache(function (err) { - if (err && err.message === "Failed to refresh slots cache.") { - redis_1.default.prototype.silentEmit.call(this, "error", err); - this.connectionPool.reset([]); - } - }.bind(this)); - this.subscriber.start(); - }) - .catch((err) => { - this.setStatus("close"); - this.handleCloseEvent(err); - this.invokeReadyDelayedCallbacks(err); - reject(err); - }); - }); - } - /** - * Called when closed to check whether a reconnection should be made - * - * @private - * @memberof Cluster - */ - handleCloseEvent(reason) { - if (reason) { - debug("closed because %s", reason); - } - let retryDelay; - if (!this.manuallyClosing && - typeof this.options.clusterRetryStrategy === "function") { - retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason); - } - if (typeof retryDelay === "number") { - this.setStatus("reconnecting"); - this.reconnectTimeout = setTimeout(function () { - this.reconnectTimeout = null; - debug("Cluster is disconnected. Retrying after %dms", retryDelay); - this.connect().catch(function (err) { - debug("Got error %s when reconnecting. Ignoring...", err); - }); - }.bind(this), retryDelay); - } - else { - this.setStatus("end"); - this.flushQueue(new Error("None of startup nodes is available")); - } - } - /** - * Disconnect from every node in the cluster. - * - * @param {boolean} [reconnect=false] - * @memberof Cluster - */ - disconnect(reconnect = false) { - const status = this.status; - this.setStatus("disconnecting"); - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - if (!reconnect) { - this.manuallyClosing = true; - } - if (this.reconnectTimeout && !reconnect) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; - debug("Canceled reconnecting attempts"); - } - this.clearNodesRefreshInterval(); - this.subscriber.stop(); - if (status === "wait") { - this.setStatus("close"); - this.handleCloseEvent(); - } - else { - this.connectionPool.reset([]); - } - } - /** - * Quit the cluster gracefully. - * - * @param {CallbackFunction<'OK'>} [callback] - * @returns {Promise<'OK'>} - * @memberof Cluster - */ - quit(callback) { - const status = this.status; - this.setStatus("disconnecting"); - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - this.manuallyClosing = true; - if (this.reconnectTimeout) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; - } - this.clearNodesRefreshInterval(); - this.subscriber.stop(); - const Promise = PromiseContainer.get(); - if (status === "wait") { - const ret = standard_as_callback_1.default(Promise.resolve("OK"), callback); - // use setImmediate to make sure "close" event - // being emitted after quit() is returned - setImmediate(function () { - this.setStatus("close"); - this.handleCloseEvent(); - }.bind(this)); - return ret; - } - return standard_as_callback_1.default(Promise.all(this.nodes().map((node) => node.quit().catch((err) => { - // Ignore the error caused by disconnecting since - // we're disconnecting... - if (err.message === utils_2.CONNECTION_CLOSED_ERROR_MSG) { - return "OK"; - } - throw err; - }))).then(() => "OK"), callback); - } - /** - * Create a new instance with the same startup nodes and options as the current one. - * - * @example - * ```js - * var cluster = new Redis.Cluster([{ host: "127.0.0.1", port: "30001" }]); - * var anotherCluster = cluster.duplicate(); - * ``` - * - * @public - * @param {((string | number | object)[])} [overrideStartupNodes=[]] - * @param {IClusterOptions} [overrideOptions={}] - * @memberof Cluster - */ - duplicate(overrideStartupNodes = [], overrideOptions = {}) { - const startupNodes = overrideStartupNodes.length > 0 - ? overrideStartupNodes - : this.startupNodes.slice(0); - const options = Object.assign({}, this.options, overrideOptions); - return new Cluster(startupNodes, options); - } - /** - * Get nodes with the specified role - * - * @param {NodeRole} [role='all'] - * @returns {any[]} - * @memberof Cluster - */ - nodes(role = "all") { - if (role !== "all" && role !== "master" && role !== "slave") { - throw new Error('Invalid role "' + role + '". Expected "all", "master" or "slave"'); - } - return this.connectionPool.getNodes(role); - } - // This is needed in order not to install a listener for each auto pipeline - delayUntilReady(callback) { - this._readyDelayedCallbacks.push(callback); - } - /** - * Get the number of commands queued in automatic pipelines. - * - * This is not available (and returns 0) until the cluster is connected and slots information have been received. - */ - get autoPipelineQueueSize() { - let queued = 0; - for (const pipeline of this._autoPipelines.values()) { - queued += pipeline.length; - } - return queued; - } - /** - * Change cluster instance's status - * - * @private - * @param {ClusterStatus} status - * @memberof Cluster - */ - setStatus(status) { - debug("status: %s -> %s", this.status || "[empty]", status); - this.status = status; - process.nextTick(() => { - this.emit(status); - }); - } - /** - * Refresh the slot cache - * - * @private - * @param {CallbackFunction} [callback] - * @memberof Cluster - */ - refreshSlotsCache(callback) { - if (this.isRefreshing) { - if (typeof callback === "function") { - process.nextTick(callback); - } - return; - } - this.isRefreshing = true; - const _this = this; - const wrapper = function (error) { - _this.isRefreshing = false; - if (typeof callback === "function") { - callback(error); - } - }; - const nodes = utils_2.shuffle(this.connectionPool.getNodes()); - let lastNodeError = null; - function tryNode(index) { - if (index === nodes.length) { - const error = new ClusterAllFailedError_1.default("Failed to refresh slots cache.", lastNodeError); - return wrapper(error); - } - const node = nodes[index]; - const key = `${node.options.host}:${node.options.port}`; - debug("getting slot cache from %s", key); - _this.getInfoFromNode(node, function (err) { - switch (_this.status) { - case "close": - case "end": - return wrapper(new Error("Cluster is disconnected.")); - case "disconnecting": - return wrapper(new Error("Cluster is disconnecting.")); - } - if (err) { - _this.emit("node error", err, key); - lastNodeError = err; - tryNode(index + 1); - } - else { - _this.emit("refresh"); - wrapper(); - } - }); - } - tryNode(0); - } - /** - * Flush offline queue with error. - * - * @param {Error} error - * @memberof Cluster - */ - flushQueue(error) { - let item; - while (this.offlineQueue.length > 0) { - item = this.offlineQueue.shift(); - item.command.reject(error); - } - } - executeOfflineCommands() { - if (this.offlineQueue.length) { - debug("send %d commands in offline queue", this.offlineQueue.length); - const offlineQueue = this.offlineQueue; - this.resetOfflineQueue(); - while (offlineQueue.length > 0) { - const item = offlineQueue.shift(); - this.sendCommand(item.command, item.stream, item.node); - } - } - } - natMapper(nodeKey) { - if (this.options.natMap && typeof this.options.natMap === "object") { - const key = typeof nodeKey === "string" - ? nodeKey - : `${nodeKey.host}:${nodeKey.port}`; - const mapped = this.options.natMap[key]; - if (mapped) { - debug("NAT mapping %s -> %O", key, mapped); - return Object.assign({}, mapped); - } - } - return typeof nodeKey === "string" - ? util_1.nodeKeyToRedisOptions(nodeKey) - : nodeKey; - } - sendCommand(command, stream, node) { - if (this.status === "wait") { - this.connect().catch(utils_1.noop); - } - if (this.status === "end") { - command.reject(new Error(utils_2.CONNECTION_CLOSED_ERROR_MSG)); - return command.promise; - } - let to = this.options.scaleReads; - if (to !== "master") { - const isCommandReadOnly = command.isReadOnly || - (commands.exists(command.name) && - commands.hasFlag(command.name, "readonly")); - if (!isCommandReadOnly) { - to = "master"; - } - } - let targetSlot = node ? node.slot : command.getSlot(); - const ttl = {}; - const _this = this; - if (!node && !command.__is_reject_overwritten) { - // eslint-disable-next-line @typescript-eslint/camelcase - command.__is_reject_overwritten = true; - const reject = command.reject; - command.reject = function (err) { - const partialTry = tryConnection.bind(null, true); - _this.handleError(err, ttl, { - moved: function (slot, key) { - debug("command %s is moved to %s", command.name, key); - targetSlot = Number(slot); - if (_this.slots[slot]) { - _this.slots[slot][0] = key; - } - else { - _this.slots[slot] = [key]; - } - _this.connectionPool.findOrCreate(_this.natMapper(key)); - tryConnection(); - debug("refreshing slot caches... (triggered by MOVED error)"); - _this.refreshSlotsCache(); - }, - ask: function (slot, key) { - debug("command %s is required to ask %s:%s", command.name, key); - const mapped = _this.natMapper(key); - _this.connectionPool.findOrCreate(mapped); - tryConnection(false, `${mapped.host}:${mapped.port}`); - }, - tryagain: partialTry, - clusterDown: partialTry, - connectionClosed: partialTry, - maxRedirections: function (redirectionError) { - reject.call(command, redirectionError); - }, - defaults: function () { - reject.call(command, err); - }, - }); - }; - } - tryConnection(); - function tryConnection(random, asking) { - if (_this.status === "end") { - command.reject(new redis_errors_1.AbortError("Cluster is ended.")); - return; - } - let redis; - if (_this.status === "ready" || command.name === "cluster") { - if (node && node.redis) { - redis = node.redis; - } - else if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", command.name) || - command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", command.name)) { - redis = _this.subscriber.getInstance(); - if (!redis) { - command.reject(new redis_errors_1.AbortError("No subscriber for the cluster")); - return; - } - } - else { - if (!random) { - if (typeof targetSlot === "number" && _this.slots[targetSlot]) { - const nodeKeys = _this.slots[targetSlot]; - if (typeof to === "function") { - const nodes = nodeKeys.map(function (key) { - return _this.connectionPool.getInstanceByKey(key); - }); - redis = to(nodes, command); - if (Array.isArray(redis)) { - redis = utils_2.sample(redis); - } - if (!redis) { - redis = nodes[0]; - } - } - else { - let key; - if (to === "all") { - key = utils_2.sample(nodeKeys); - } - else if (to === "slave" && nodeKeys.length > 1) { - key = utils_2.sample(nodeKeys, 1); - } - else { - key = nodeKeys[0]; - } - redis = _this.connectionPool.getInstanceByKey(key); - } - } - if (asking) { - redis = _this.connectionPool.getInstanceByKey(asking); - redis.asking(); - } - } - if (!redis) { - redis = - (typeof to === "function" - ? null - : _this.connectionPool.getSampleInstance(to)) || - _this.connectionPool.getSampleInstance("all"); - } - } - if (node && !node.redis) { - node.redis = redis; - } - } - if (redis) { - redis.sendCommand(command, stream); - } - else if (_this.options.enableOfflineQueue) { - _this.offlineQueue.push({ - command: command, - stream: stream, - node: node, - }); - } - else { - command.reject(new Error("Cluster isn't ready and enableOfflineQueue options is false")); - } - } - return command.promise; - } - handleError(error, ttl, handlers) { - if (typeof ttl.value === "undefined") { - ttl.value = this.options.maxRedirections; - } - else { - ttl.value -= 1; - } - if (ttl.value <= 0) { - handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); - return; - } - const errv = error.message.split(" "); - if (errv[0] === "MOVED" || errv[0] === "ASK") { - handlers[errv[0] === "MOVED" ? "moved" : "ask"](errv[1], errv[2]); - } - else if (errv[0] === "TRYAGAIN") { - this.delayQueue.push("tryagain", handlers.tryagain, { - timeout: this.options.retryDelayOnTryAgain, - }); - } - else if (errv[0] === "CLUSTERDOWN" && - this.options.retryDelayOnClusterDown > 0) { - this.delayQueue.push("clusterdown", handlers.connectionClosed, { - timeout: this.options.retryDelayOnClusterDown, - callback: this.refreshSlotsCache.bind(this), - }); - } - else if (error.message === utils_2.CONNECTION_CLOSED_ERROR_MSG && - this.options.retryDelayOnFailover > 0 && - this.status === "ready") { - this.delayQueue.push("failover", handlers.connectionClosed, { - timeout: this.options.retryDelayOnFailover, - callback: this.refreshSlotsCache.bind(this), - }); - } - else { - handlers.defaults(); - } - } - getInfoFromNode(redis, callback) { - if (!redis) { - return callback(new Error("Node is disconnected")); - } - // Use a duplication of the connection to avoid - // timeouts when the connection is in the blocking - // mode (e.g. waiting for BLPOP). - const duplicatedConnection = redis.duplicate({ - enableOfflineQueue: true, - enableReadyCheck: false, - retryStrategy: null, - connectionName: "ioredisClusterRefresher", - }); - // Ignore error events since we will handle - // exceptions for the CLUSTER SLOTS command. - duplicatedConnection.on("error", utils_1.noop); - duplicatedConnection.cluster("slots", utils_2.timeout((err, result) => { - duplicatedConnection.disconnect(); - if (err) { - return callback(err); - } - if (this.status === "disconnecting" || - this.status === "close" || - this.status === "end") { - debug("ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s", result.length, this.status); - callback(); - return; - } - const nodes = []; - debug("cluster slots result count: %d", result.length); - for (let i = 0; i < result.length; ++i) { - const items = result[i]; - const slotRangeStart = items[0]; - const slotRangeEnd = items[1]; - const keys = []; - for (let j = 2; j < items.length; j++) { - if (!items[j][0]) { - continue; - } - items[j] = this.natMapper({ host: items[j][0], port: items[j][1] }); - items[j].readOnly = j !== 2; - nodes.push(items[j]); - keys.push(items[j].host + ":" + items[j].port); - } - debug("cluster slots result [%d]: slots %d~%d served by %s", i, slotRangeStart, slotRangeEnd, keys); - for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) { - this.slots[slot] = keys; - } - } - this.connectionPool.reset(nodes); - callback(); - }, this.options.slotsRefreshTimeout)); - } - invokeReadyDelayedCallbacks(err) { - for (const c of this._readyDelayedCallbacks) { - process.nextTick(c, err); - } - this._readyDelayedCallbacks = []; - } - /** - * Check whether Cluster is able to process commands - * - * @param {Function} callback - * @private - */ - readyCheck(callback) { - this.cluster("info", function (err, res) { - if (err) { - return callback(err); - } - if (typeof res !== "string") { - return callback(); - } - let state; - const lines = res.split("\r\n"); - for (let i = 0; i < lines.length; ++i) { - const parts = lines[i].split(":"); - if (parts[0] === "cluster_state") { - state = parts[1]; - break; - } - } - if (state === "fail") { - debug("cluster state not ok (%s)", state); - callback(null, state); - } - else { - callback(); - } - }); - } - dnsLookup(hostname) { - return new Promise((resolve, reject) => { - this.options.dnsLookup(hostname, (err, address) => { - if (err) { - debug("failed to resolve hostname %s to IP: %s", hostname, err.message); - reject(err); - } - else { - debug("resolved hostname %s to IP %s", hostname, address); - resolve(address); - } - }); - }); - } - /** - * Normalize startup nodes, and resolving hostnames to IPs. - * - * This process happens every time when #connect() is called since - * #startupNodes and DNS records may chanage. - * - * @private - * @returns {Promise} - */ - resolveStartupNodeHostnames() { - if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) { - return Promise.reject(new Error("`startupNodes` should contain at least one node.")); - } - const startupNodes = util_1.normalizeNodeOptions(this.startupNodes); - const hostnames = util_1.getUniqueHostnamesFromOptions(startupNodes); - if (hostnames.length === 0) { - return Promise.resolve(startupNodes); - } - return Promise.all(hostnames.map((hostname) => this.dnsLookup(hostname))).then((ips) => { - const hostnameToIP = utils_2.zipMap(hostnames, ips); - return startupNodes.map((node) => hostnameToIP.has(node.host) - ? Object.assign({}, node, { host: hostnameToIP.get(node.host) }) - : node); - }); - } -} -Object.getOwnPropertyNames(commander_1.default.prototype).forEach((name) => { - if (!Cluster.prototype.hasOwnProperty(name)) { - Cluster.prototype[name] = commander_1.default.prototype[name]; - } -}); -const scanCommands = [ - "sscan", - "hscan", - "zscan", - "sscanBuffer", - "hscanBuffer", - "zscanBuffer", -]; -scanCommands.forEach((command) => { - Cluster.prototype[command + "Stream"] = function (key, options) { - return new ScanStream_1.default(utils_1.defaults({ - objectMode: true, - key: key, - redis: this, - command: command, - }, options)); - }; -}); -__nccwpck_require__(14645).addTransactionSupport(Cluster.prototype); -exports.default = Cluster; - - -/***/ }), - -/***/ 94582: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const net_1 = __nccwpck_require__(11631); -function getNodeKey(node) { - node.port = node.port || 6379; - node.host = node.host || "127.0.0.1"; - return node.host + ":" + node.port; -} -exports.getNodeKey = getNodeKey; -function nodeKeyToRedisOptions(nodeKey) { - const portIndex = nodeKey.lastIndexOf(":"); - if (portIndex === -1) { - throw new Error(`Invalid node key ${nodeKey}`); - } - return { - host: nodeKey.slice(0, portIndex), - port: Number(nodeKey.slice(portIndex + 1)), - }; -} -exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; -function normalizeNodeOptions(nodes) { - return nodes.map((node) => { - const options = {}; - if (typeof node === "object") { - Object.assign(options, node); - } - else if (typeof node === "string") { - Object.assign(options, utils_1.parseURL(node)); - } - else if (typeof node === "number") { - options.port = node; - } - else { - throw new Error("Invalid argument " + node); - } - if (typeof options.port === "string") { - options.port = parseInt(options.port, 10); - } - // Cluster mode only support db 0 - delete options.db; - if (!options.port) { - options.port = 6379; - } - if (!options.host) { - options.host = "127.0.0.1"; - } - return options; - }); -} -exports.normalizeNodeOptions = normalizeNodeOptions; -function getUniqueHostnamesFromOptions(nodes) { - const uniqueHostsMap = {}; - nodes.forEach((node) => { - uniqueHostsMap[node.host] = true; - }); - return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); -} -exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; - - -/***/ }), - -/***/ 90803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const commands = __nccwpck_require__(98020); -const calculateSlot = __nccwpck_require__(48481); -const standard_as_callback_1 = __nccwpck_require__(91543); -const utils_1 = __nccwpck_require__(94832); -const lodash_1 = __nccwpck_require__(20961); -const promiseContainer_1 = __nccwpck_require__(71475); -/** - * Command instance - * - * It's rare that you need to create a Command instance yourself. - * - * @export - * @class Command - * - * @example - * ```js - * var infoCommand = new Command('info', null, function (err, result) { - * console.log('result', result); - * }); - * - * redis.sendCommand(infoCommand); - * - * // When no callback provided, Command instance will have a `promise` property, - * // which will resolve/reject with the result of the command. - * var getCommand = new Command('get', ['foo']); - * getCommand.promise.then(function (result) { - * console.log('result', result); - * }); - * ``` - * @see {@link Redis#sendCommand} which can send a Command instance to Redis - */ -class Command { - /** - * Creates an instance of Command. - * @param {string} name Command name - * @param {(Array)} [args=[]] An array of command arguments - * @param {ICommandOptions} [options={}] - * @param {CallbackFunction} [callback] The callback that handles the response. - * If omit, the response will be handled via Promise - * @memberof Command - */ - constructor(name, args = [], options = {}, callback) { - this.name = name; - this.transformed = false; - this.isCustomCommand = false; - this.inTransaction = false; - this.replyEncoding = options.replyEncoding; - this.errorStack = options.errorStack; - this.args = lodash_1.flatten(args); - this.callback = callback; - this.initPromise(); - if (options.keyPrefix) { - this._iterateKeys((key) => options.keyPrefix + key); - } - if (options.readOnly) { - this.isReadOnly = true; - } - } - static getFlagMap() { - if (!this.flagMap) { - this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { - map[flagName] = {}; - Command.FLAGS[flagName].forEach((commandName) => { - map[flagName][commandName] = true; - }); - return map; - }, {}); - } - return this.flagMap; - } - /** - * Check whether the command has the flag - * - * @param {string} flagName - * @param {string} commandName - * @return {boolean} - */ - static checkFlag(flagName, commandName) { - return !!this.getFlagMap()[flagName][commandName]; - } - static setArgumentTransformer(name, func) { - this._transformer.argument[name] = func; - } - static setReplyTransformer(name, func) { - this._transformer.reply[name] = func; - } - initPromise() { - const Promise = promiseContainer_1.get(); - const promise = new Promise((resolve, reject) => { - if (!this.transformed) { - this.transformed = true; - const transformer = Command._transformer.argument[this.name]; - if (transformer) { - this.args = transformer(this.args); - } - this.stringifyArguments(); - } - this.resolve = this._convertValue(resolve); - if (this.errorStack) { - this.reject = (err) => { - reject(utils_1.optimizeErrorStack(err, this.errorStack, __dirname)); - }; - } - else { - this.reject = reject; - } - }); - this.promise = standard_as_callback_1.default(promise, this.callback); - } - getSlot() { - if (typeof this.slot === "undefined") { - const key = this.getKeys()[0]; - this.slot = key == null ? null : calculateSlot(key); - } - return this.slot; - } - getKeys() { - return this._iterateKeys(); - } - /** - * Iterate through the command arguments that are considered keys. - * - * @param {Function} [transform=(key) => key] The transformation that should be applied to - * each key. The transformations will persist. - * @returns {string[]} The keys of the command. - * @memberof Command - */ - _iterateKeys(transform = (key) => key) { - if (typeof this.keys === "undefined") { - this.keys = []; - if (commands.exists(this.name)) { - const keyIndexes = commands.getKeyIndexes(this.name, this.args); - for (const index of keyIndexes) { - this.args[index] = transform(this.args[index]); - this.keys.push(this.args[index]); - } - } - } - return this.keys; - } - /** - * Convert command to writable buffer or string - * - * @return {string|Buffer} - * @see {@link Redis#sendCommand} - * @public - */ - toWritable() { - let bufferMode = false; - for (const arg of this.args) { - if (arg instanceof Buffer) { - bufferMode = true; - break; - } - } - let result; - const commandStr = "*" + - (this.args.length + 1) + - "\r\n$" + - Buffer.byteLength(this.name) + - "\r\n" + - this.name + - "\r\n"; - if (bufferMode) { - const buffers = new MixedBuffers(); - buffers.push(commandStr); - for (const arg of this.args) { - if (arg instanceof Buffer) { - if (arg.length === 0) { - buffers.push("$0\r\n\r\n"); - } - else { - buffers.push("$" + arg.length + "\r\n"); - buffers.push(arg); - buffers.push("\r\n"); - } - } - else { - buffers.push("$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"); - } - } - result = buffers.toBuffer(); - } - else { - result = commandStr; - for (const arg of this.args) { - result += - "$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"; - } - } - return result; - } - stringifyArguments() { - for (let i = 0; i < this.args.length; ++i) { - const arg = this.args[i]; - if (!(arg instanceof Buffer) && typeof arg !== "string") { - this.args[i] = utils_1.toArg(arg); - } - } - } - /** - * Convert the value from buffer to the target encoding. - * - * @private - * @param {Function} resolve The resolve function of the Promise - * @returns {Function} A function to transform and resolve a value - * @memberof Command - */ - _convertValue(resolve) { - return (value) => { - try { - resolve(this.transformReply(value)); - } - catch (err) { - this.reject(err); - } - return this.promise; - }; - } - /** - * Convert buffer/buffer[] to string/string[], - * and apply reply transformer. - * - * @memberof Command - */ - transformReply(result) { - if (this.replyEncoding) { - result = utils_1.convertBufferToString(result, this.replyEncoding); - } - const transformer = Command._transformer.reply[this.name]; - if (transformer) { - result = transformer(result); - } - return result; - } -} -exports.default = Command; -Command.FLAGS = { - VALID_IN_SUBSCRIBER_MODE: [ - "subscribe", - "psubscribe", - "unsubscribe", - "punsubscribe", - "ping", - "quit", - ], - VALID_IN_MONITOR_MODE: ["monitor", "auth"], - ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], - EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], - WILL_DISCONNECT: ["quit"], -}; -Command._transformer = { - argument: {}, - reply: {}, -}; -const msetArgumentTransformer = function (args) { - if (args.length === 1) { - if (typeof Map !== "undefined" && args[0] instanceof Map) { - return utils_1.convertMapToArray(args[0]); - } - if (typeof args[0] === "object" && args[0] !== null) { - return utils_1.convertObjectToArray(args[0]); - } - } - return args; -}; -Command.setArgumentTransformer("mset", msetArgumentTransformer); -Command.setArgumentTransformer("msetnx", msetArgumentTransformer); -Command.setArgumentTransformer("hmset", function (args) { - if (args.length === 2) { - if (typeof Map !== "undefined" && args[1] instanceof Map) { - return [args[0]].concat(utils_1.convertMapToArray(args[1])); - } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); - } - } - return args; -}); -Command.setReplyTransformer("hgetall", function (result) { - if (Array.isArray(result)) { - const obj = {}; - for (let i = 0; i < result.length; i += 2) { - obj[result[i]] = result[i + 1]; - } - return obj; - } - return result; -}); -Command.setArgumentTransformer("hset", function (args) { - if (args.length === 2) { - if (typeof Map !== "undefined" && args[1] instanceof Map) { - return [args[0]].concat(utils_1.convertMapToArray(args[1])); - } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); - } - } - return args; -}); -class MixedBuffers { - constructor() { - this.length = 0; - this.items = []; - } - push(x) { - this.length += Buffer.byteLength(x); - this.items.push(x); - } - toBuffer() { - const result = Buffer.allocUnsafe(this.length); - let offset = 0; - for (const item of this.items) { - const length = Buffer.byteLength(item); - Buffer.isBuffer(item) - ? item.copy(result, offset) - : result.write(item, offset, length); - offset += length; - } - return result; - } -} - - -/***/ }), - -/***/ 33642: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lodash_1 = __nccwpck_require__(20961); -const command_1 = __nccwpck_require__(90803); -const script_1 = __nccwpck_require__(88540); -const PromiseContainer = __nccwpck_require__(71475); -const standard_as_callback_1 = __nccwpck_require__(91543); -const autoPipelining_1 = __nccwpck_require__(97873); -const DROP_BUFFER_SUPPORT_ERROR = "*Buffer methods are not available " + - 'because "dropBufferSupport" option is enabled.' + - "Refer to https://github.com/luin/ioredis/wiki/Improve-Performance for more details."; -/** - * Commander - * - * This is the base class of Redis, Redis.Cluster and Pipeline - * - * @param {boolean} [options.showFriendlyErrorStack=false] - Whether to show a friendly error stack. - * Will decrease the performance significantly. - * @constructor - */ -function Commander() { - this.options = lodash_1.defaults({}, this.options || {}, { - showFriendlyErrorStack: false, - }); - this.scriptsSet = {}; -} -exports.default = Commander; -const commands = __nccwpck_require__(98020).list.filter(function (command) { - return command !== "monitor"; -}); -commands.push("sentinel"); -/** - * Return supported builtin commands - * - * @return {string[]} command list - * @public - */ -Commander.prototype.getBuiltinCommands = function () { - return commands.slice(0); -}; -/** - * Create a builtin command - * - * @param {string} commandName - command name - * @return {object} functions - * @public - */ -Commander.prototype.createBuiltinCommand = function (commandName) { - return { - string: generateFunction(commandName, "utf8"), - buffer: generateFunction(commandName, null), - }; -}; -commands.forEach(function (commandName) { - Commander.prototype[commandName] = generateFunction(commandName, "utf8"); - Commander.prototype[commandName + "Buffer"] = generateFunction(commandName, null); -}); -Commander.prototype.call = generateFunction("utf8"); -Commander.prototype.callBuffer = generateFunction(null); -// eslint-disable-next-line @typescript-eslint/camelcase -Commander.prototype.send_command = Commander.prototype.call; -/** - * Define a custom command using lua script - * - * @param {string} name - the command name - * @param {object} definition - * @param {string} definition.lua - the lua code - * @param {number} [definition.numberOfKeys=null] - the number of keys. - * @param {boolean} [definition.readOnly=false] - force this script to be readonly so it executes on slaves as well. - * If omit, you have to pass the number of keys as the first argument every time you invoke the command - */ -Commander.prototype.defineCommand = function (name, definition) { - const script = new script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly); - this.scriptsSet[name] = script; - this[name] = generateScriptingFunction(name, script, "utf8"); - this[name + "Buffer"] = generateScriptingFunction(name, script, null); -}; -/** - * Send a command - * - * @abstract - * @public - */ -Commander.prototype.sendCommand = function () { }; -function generateFunction(_commandName, _encoding) { - if (typeof _encoding === "undefined") { - _encoding = _commandName; - _commandName = null; - } - return function (...args) { - const commandName = _commandName || args.shift(); - let callback = args[args.length - 1]; - if (typeof callback === "function") { - args.pop(); - } - else { - callback = undefined; - } - const options = { - errorStack: this.options.showFriendlyErrorStack - ? new Error().stack - : undefined, - keyPrefix: this.options.keyPrefix, - replyEncoding: _encoding, - }; - if (this.options.dropBufferSupport && !_encoding) { - return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); - } - // No auto pipeline, use regular command sending - if (!autoPipelining_1.shouldUseAutoPipelining(this, commandName)) { - return this.sendCommand(new command_1.default(commandName, args, options, callback)); - } - // Create a new pipeline and make sure it's scheduled - return autoPipelining_1.executeWithAutoPipelining(this, commandName, args, callback); - }; -} -function generateScriptingFunction(name, script, encoding) { - return function () { - let length = arguments.length; - const lastArgIndex = length - 1; - let callback = arguments[lastArgIndex]; - if (typeof callback !== "function") { - callback = undefined; - } - else { - length = lastArgIndex; - } - const args = new Array(length); - for (let i = 0; i < length; i++) { - args[i] = arguments[i]; - } - let options; - if (this.options.dropBufferSupport) { - if (!encoding) { - return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); - } - options = { replyEncoding: null }; - } - else { - options = { replyEncoding: encoding }; - } - if (this.options.showFriendlyErrorStack) { - options.errorStack = new Error().stack; - } - // No auto pipeline, use regular command sending - if (!autoPipelining_1.shouldUseAutoPipelining(this, name)) { - return script.execute(this, args, options, callback); - } - // Create a new pipeline and make sure it's scheduled - return autoPipelining_1.executeWithAutoPipelining(this, name, args, callback); - }; -} - - -/***/ }), - -/***/ 72712: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class AbstractConnector { - constructor() { - this.connecting = false; - } - check(info) { - return true; - } - disconnect() { - this.connecting = false; - if (this.stream) { - this.stream.end(); - } - } -} -exports.default = AbstractConnector; - - -/***/ }), - -/***/ 72225: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isSentinelEql(a, b) { - return ((a.host || "127.0.0.1") === (b.host || "127.0.0.1") && - (a.port || 26379) === (b.port || 26379)); -} -class SentinelIterator { - constructor(sentinels) { - this.cursor = 0; - this.sentinels = sentinels.slice(0); - } - next() { - const done = this.cursor >= this.sentinels.length; - return { done, value: done ? undefined : this.sentinels[this.cursor++] }; - } - reset(moveCurrentEndpointToFirst) { - if (moveCurrentEndpointToFirst && - this.sentinels.length > 1 && - this.cursor !== 1) { - this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1)); - } - this.cursor = 0; - } - add(sentinel) { - for (let i = 0; i < this.sentinels.length; i++) { - if (isSentinelEql(sentinel, this.sentinels[i])) { - return false; - } - } - this.sentinels.push(sentinel); - return true; - } - toString() { - return `${JSON.stringify(this.sentinels)} @${this.cursor}`; - } -} -exports.default = SentinelIterator; - - -/***/ }), - -/***/ 10379: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __nccwpck_require__(11631); -const utils_1 = __nccwpck_require__(94832); -const tls_1 = __nccwpck_require__(4016); -const StandaloneConnector_1 = __nccwpck_require__(8774); -const SentinelIterator_1 = __nccwpck_require__(72225); -exports.SentinelIterator = SentinelIterator_1.default; -const AbstractConnector_1 = __nccwpck_require__(72712); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("SentinelConnector"); -class SentinelConnector extends AbstractConnector_1.default { - constructor(options) { - super(); - this.options = options; - if (!this.options.sentinels.length) { - throw new Error("Requires at least one sentinel to connect to."); - } - if (!this.options.name) { - throw new Error("Requires the name of master."); - } - this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels); - } - check(info) { - const roleMatches = !info.role || this.options.role === info.role; - if (!roleMatches) { - debug("role invalid, expected %s, but got %s", this.options.role, info.role); - // Start from the next item. - // Note that `reset` will move the cursor to the previous element, - // so we advance two steps here. - this.sentinelIterator.next(); - this.sentinelIterator.next(); - this.sentinelIterator.reset(true); - } - return roleMatches; - } - connect(eventEmitter) { - this.connecting = true; - this.retryAttempts = 0; - let lastError; - const connectToNext = () => new Promise((resolve, reject) => { - const endpoint = this.sentinelIterator.next(); - if (endpoint.done) { - this.sentinelIterator.reset(false); - const retryDelay = typeof this.options.sentinelRetryStrategy === "function" - ? this.options.sentinelRetryStrategy(++this.retryAttempts) - : null; - let errorMsg = typeof retryDelay !== "number" - ? "All sentinels are unreachable and retry is disabled." - : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`; - if (lastError) { - errorMsg += ` Last error: ${lastError.message}`; - } - debug(errorMsg); - const error = new Error(errorMsg); - if (typeof retryDelay === "number") { - setTimeout(() => { - resolve(connectToNext()); - }, retryDelay); - eventEmitter("error", error); - } - else { - reject(error); - } - return; - } - this.resolve(endpoint.value, (err, resolved) => { - if (!this.connecting) { - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return; - } - if (resolved) { - debug("resolved: %s:%s", resolved.host, resolved.port); - if (this.options.enableTLSForSentinelMode && this.options.tls) { - Object.assign(resolved, this.options.tls); - this.stream = tls_1.connect(resolved); - } - else { - this.stream = net_1.createConnection(resolved); - } - this.sentinelIterator.reset(true); - resolve(this.stream); - } - else { - const endpointAddress = endpoint.value.host + ":" + endpoint.value.port; - const errorMsg = err - ? "failed to connect to sentinel " + - endpointAddress + - " because " + - err.message - : "connected to sentinel " + - endpointAddress + - " successfully, but got an invalid reply: " + - resolved; - debug(errorMsg); - eventEmitter("sentinelError", new Error(errorMsg)); - if (err) { - lastError = err; - } - resolve(connectToNext()); - } - }); - }); - return connectToNext(); - } - updateSentinels(client, callback) { - if (!this.options.updateSentinels) { - return callback(null); - } - client.sentinel("sentinels", this.options.name, (err, result) => { - if (err) { - client.disconnect(); - return callback(err); - } - if (!Array.isArray(result)) { - return callback(null); - } - result - .map(utils_1.packObject) - .forEach((sentinel) => { - const flags = sentinel.flags ? sentinel.flags.split(",") : []; - if (flags.indexOf("disconnected") === -1 && - sentinel.ip && - sentinel.port) { - const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel)); - if (this.sentinelIterator.add(endpoint)) { - debug("adding sentinel %s:%s", endpoint.host, endpoint.port); - } - } - }); - debug("Updated internal sentinels: %s", this.sentinelIterator); - callback(null); - }); - } - resolveMaster(client, callback) { - client.sentinel("get-master-addr-by-name", this.options.name, (err, result) => { - if (err) { - client.disconnect(); - return callback(err); - } - this.updateSentinels(client, (err) => { - client.disconnect(); - if (err) { - return callback(err); - } - callback(null, this.sentinelNatResolve(Array.isArray(result) - ? { host: result[0], port: Number(result[1]) } - : null)); - }); - }); - } - resolveSlave(client, callback) { - client.sentinel("slaves", this.options.name, (err, result) => { - client.disconnect(); - if (err) { - return callback(err); - } - if (!Array.isArray(result)) { - return callback(null, null); - } - const availableSlaves = result - .map(utils_1.packObject) - .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)); - callback(null, this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves))); - }); - } - sentinelNatResolve(item) { - if (!item || !this.options.natMap) - return item; - return this.options.natMap[`${item.host}:${item.port}`] || item; - } - resolve(endpoint, callback) { - const client = new redis_1.default({ - port: endpoint.port || 26379, - host: endpoint.host, - username: this.options.sentinelUsername || null, - password: this.options.sentinelPassword || null, - family: endpoint.family || - (StandaloneConnector_1.isIIpcConnectionOptions(this.options) - ? undefined - : this.options.family), - tls: this.options.sentinelTLS, - retryStrategy: null, - enableReadyCheck: false, - connectTimeout: this.options.connectTimeout, - dropBufferSupport: true, - }); - // ignore the errors since resolve* methods will handle them - client.on("error", noop); - if (this.options.role === "slave") { - this.resolveSlave(client, callback); - } - else { - this.resolveMaster(client, callback); - } - } -} -exports.default = SentinelConnector; -function selectPreferredSentinel(availableSlaves, preferredSlaves) { - if (availableSlaves.length === 0) { - return null; - } - let selectedSlave; - if (typeof preferredSlaves === "function") { - selectedSlave = preferredSlaves(availableSlaves); - } - else if (preferredSlaves !== null && typeof preferredSlaves === "object") { - const preferredSlavesArray = Array.isArray(preferredSlaves) - ? preferredSlaves - : [preferredSlaves]; - // sort by priority - preferredSlavesArray.sort((a, b) => { - // default the priority to 1 - if (!a.prio) { - a.prio = 1; - } - if (!b.prio) { - b.prio = 1; - } - // lowest priority first - if (a.prio < b.prio) { - return -1; - } - if (a.prio > b.prio) { - return 1; - } - return 0; - }); - // loop over preferred slaves and return the first match - for (let p = 0; p < preferredSlavesArray.length; p++) { - for (let a = 0; a < availableSlaves.length; a++) { - const slave = availableSlaves[a]; - if (slave.ip === preferredSlavesArray[p].ip) { - if (slave.port === preferredSlavesArray[p].port) { - selectedSlave = slave; - break; - } - } - } - if (selectedSlave) { - break; - } - } - } - // if none of the preferred slaves are available, a random available slave is returned - if (!selectedSlave) { - selectedSlave = utils_1.sample(availableSlaves); - } - return addressResponseToAddress(selectedSlave); -} -function addressResponseToAddress(input) { - return { host: input.ip, port: Number(input.port) }; -} -function noop() { } - - -/***/ }), - -/***/ 8774: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __nccwpck_require__(11631); -const tls_1 = __nccwpck_require__(4016); -const utils_1 = __nccwpck_require__(94832); -const AbstractConnector_1 = __nccwpck_require__(72712); -function isIIpcConnectionOptions(value) { - return value.path; -} -exports.isIIpcConnectionOptions = isIIpcConnectionOptions; -class StandaloneConnector extends AbstractConnector_1.default { - constructor(options) { - super(); - this.options = options; - } - connect(_) { - const { options } = this; - this.connecting = true; - let connectionOptions; - if (isIIpcConnectionOptions(options)) { - connectionOptions = { - path: options.path, - }; - } - else { - connectionOptions = {}; - if (options.port != null) { - connectionOptions.port = options.port; - } - if (options.host != null) { - connectionOptions.host = options.host; - } - if (options.family != null) { - connectionOptions.family = options.family; - } - } - if (options.tls) { - Object.assign(connectionOptions, options.tls); - } - // TODO: - // We use native Promise here since other Promise - // implementation may use different schedulers that - // cause issue when the stream is resolved in the - // next tick. - // Should use the provided promise in the next major - // version and do not connect before resolved. - return new Promise((resolve, reject) => { - process.nextTick(() => { - if (!this.connecting) { - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return; - } - try { - if (options.tls) { - this.stream = tls_1.connect(connectionOptions); - } - else { - this.stream = net_1.createConnection(connectionOptions); - } - } - catch (err) { - reject(err); - return; - } - resolve(this.stream); - }); - }); - } -} -exports.default = StandaloneConnector; - - -/***/ }), - -/***/ 72340: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const StandaloneConnector_1 = __nccwpck_require__(8774); -exports.StandaloneConnector = StandaloneConnector_1.default; -const SentinelConnector_1 = __nccwpck_require__(10379); -exports.SentinelConnector = SentinelConnector_1.default; - - -/***/ }), - -/***/ 97282: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -class ClusterAllFailedError extends redis_errors_1.RedisError { - constructor(message, lastNodeError) { - super(message); - this.lastNodeError = lastNodeError; - Error.captureStackTrace(this, this.constructor); - } - get name() { - return this.constructor.name; - } -} -exports.default = ClusterAllFailedError; - - -/***/ }), - -/***/ 90735: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -class MaxRetriesPerRequestError extends redis_errors_1.AbortError { - constructor(maxRetriesPerRequest) { - const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to "maxRetriesPerRequest" option for details.`; - super(message); - Error.captureStackTrace(this, this.constructor); - } - get name() { - return this.constructor.name; - } -} -exports.default = MaxRetriesPerRequestError; - - -/***/ }), - -/***/ 23961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); -exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; - - -/***/ }), - -/***/ 45069: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports = module.exports = __nccwpck_require__(83609).default; -var redis_1 = __nccwpck_require__(83609); -exports.default = redis_1.default; -var cluster_1 = __nccwpck_require__(17208); -exports.Cluster = cluster_1.default; -var command_1 = __nccwpck_require__(90803); -exports.Command = command_1.default; -var ScanStream_1 = __nccwpck_require__(6134); -exports.ScanStream = ScanStream_1.default; -var pipeline_1 = __nccwpck_require__(42803); -exports.Pipeline = pipeline_1.default; -var AbstractConnector_1 = __nccwpck_require__(72712); -exports.AbstractConnector = AbstractConnector_1.default; -var SentinelConnector_1 = __nccwpck_require__(10379); -exports.SentinelConnector = SentinelConnector_1.default; -exports.SentinelIterator = SentinelConnector_1.SentinelIterator; -// No TS typings -exports.ReplyError = __nccwpck_require__(81879).ReplyError; -const PromiseContainer = __nccwpck_require__(71475); -Object.defineProperty(exports, "Promise", ({ - get() { - return PromiseContainer.get(); - }, - set(lib) { - PromiseContainer.set(lib); - }, -})); -function print(err, reply) { - if (err) { - console.log("Error: " + err); - } - else { - console.log("Reply: " + reply); - } -} -exports.print = print; - - -/***/ }), - -/***/ 42803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(90803); -const util_1 = __nccwpck_require__(31669); -const standard_as_callback_1 = __nccwpck_require__(91543); -const redis_commands_1 = __nccwpck_require__(98020); -const calculateSlot = __nccwpck_require__(48481); -const pMap = __nccwpck_require__(91855); -const PromiseContainer = __nccwpck_require__(71475); -const commander_1 = __nccwpck_require__(33642); -/* - This function derives from the cluster-key-slot implementation. - Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes. - If this is satisfied, it returns the first key's slot. -*/ -function generateMultiWithNodes(redis, keys) { - const slot = calculateSlot(keys[0]); - const target = redis.slots[slot].join(","); - for (let i = 1; i < keys.length; i++) { - const currentTarget = redis.slots[calculateSlot(keys[i])].join(","); - if (currentTarget !== target) { - return -1; - } - } - return slot; -} -function Pipeline(redis) { - commander_1.default.call(this); - this.redis = redis; - this.isCluster = this.redis.constructor.name === "Cluster"; - this.isPipeline = true; - this.options = redis.options; - this._queue = []; - this._result = []; - this._transactions = 0; - this._shaToScript = {}; - Object.keys(redis.scriptsSet).forEach((name) => { - const script = redis.scriptsSet[name]; - this._shaToScript[script.sha] = script; - this[name] = redis[name]; - this[name + "Buffer"] = redis[name + "Buffer"]; - }); - const Promise = PromiseContainer.get(); - this.promise = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - const _this = this; - Object.defineProperty(this, "length", { - get: function () { - return _this._queue.length; - }, - }); -} -exports.default = Pipeline; -Object.assign(Pipeline.prototype, commander_1.default.prototype); -Pipeline.prototype.fillResult = function (value, position) { - if (this._queue[position].name === "exec" && Array.isArray(value[1])) { - const execLength = value[1].length; - for (let i = 0; i < execLength; i++) { - if (value[1][i] instanceof Error) { - continue; - } - const cmd = this._queue[position - (execLength - i)]; - try { - value[1][i] = cmd.transformReply(value[1][i]); - } - catch (err) { - value[1][i] = err; - } - } - } - this._result[position] = value; - if (--this.replyPending) { - return; - } - if (this.isCluster) { - let retriable = true; - let commonError; - for (let i = 0; i < this._result.length; ++i) { - const error = this._result[i][0]; - const command = this._queue[i]; - if (error) { - if (command.name === "exec" && - error.message === - "EXECABORT Transaction discarded because of previous errors.") { - continue; - } - if (!commonError) { - commonError = { - name: error.name, - message: error.message, - }; - } - else if (commonError.name !== error.name || - commonError.message !== error.message) { - retriable = false; - break; - } - } - else if (!command.inTransaction) { - const isReadOnly = redis_commands_1.exists(command.name) && redis_commands_1.hasFlag(command.name, "readonly"); - if (!isReadOnly) { - retriable = false; - break; - } - } - } - if (commonError && retriable) { - const _this = this; - const errv = commonError.message.split(" "); - const queue = this._queue; - let inTransaction = false; - this._queue = []; - for (let i = 0; i < queue.length; ++i) { - if (errv[0] === "ASK" && - !inTransaction && - queue[i].name !== "asking" && - (!queue[i - 1] || queue[i - 1].name !== "asking")) { - const asking = new command_1.default("asking"); - asking.ignore = true; - this.sendCommand(asking); - } - queue[i].initPromise(); - this.sendCommand(queue[i]); - inTransaction = queue[i].inTransaction; - } - let matched = true; - if (typeof this.leftRedirections === "undefined") { - this.leftRedirections = {}; - } - const exec = function () { - _this.exec(); - }; - this.redis.handleError(commonError, this.leftRedirections, { - moved: function (slot, key) { - _this.preferKey = key; - _this.redis.slots[errv[1]] = [key]; - _this.redis.refreshSlotsCache(); - _this.exec(); - }, - ask: function (slot, key) { - _this.preferKey = key; - _this.exec(); - }, - tryagain: exec, - clusterDown: exec, - connectionClosed: exec, - maxRedirections: () => { - matched = false; - }, - defaults: () => { - matched = false; - }, - }); - if (matched) { - return; - } - } - } - let ignoredCount = 0; - for (let i = 0; i < this._queue.length - ignoredCount; ++i) { - if (this._queue[i + ignoredCount].ignore) { - ignoredCount += 1; - } - this._result[i] = this._result[i + ignoredCount]; - } - this.resolve(this._result.slice(0, this._result.length - ignoredCount)); -}; -Pipeline.prototype.sendCommand = function (command) { - if (this._transactions > 0) { - command.inTransaction = true; - } - const position = this._queue.length; - command.pipelineIndex = position; - command.promise - .then((result) => { - this.fillResult([null, result], position); - }) - .catch((error) => { - this.fillResult([error], position); - }); - this._queue.push(command); - return this; -}; -Pipeline.prototype.addBatch = function (commands) { - let command, commandName, args; - for (let i = 0; i < commands.length; ++i) { - command = commands[i]; - commandName = command[0]; - args = command.slice(1); - this[commandName].apply(this, args); - } - return this; -}; -const multi = Pipeline.prototype.multi; -Pipeline.prototype.multi = function () { - this._transactions += 1; - return multi.apply(this, arguments); -}; -const execBuffer = Pipeline.prototype.execBuffer; -const exec = Pipeline.prototype.exec; -Pipeline.prototype.execBuffer = util_1.deprecate(function () { - if (this._transactions > 0) { - this._transactions -= 1; - } - return execBuffer.apply(this, arguments); -}, "Pipeline#execBuffer: Use Pipeline#exec instead"); -Pipeline.prototype.exec = function (callback) { - // Wait for the cluster to be connected, since we need nodes information before continuing - if (this.isCluster && !this.redis.slots.length) { - this.redis.delayUntilReady((err) => { - if (err) { - callback(err); - return; - } - this.exec(callback); - }); - return this.promise; - } - if (this._transactions > 0) { - this._transactions -= 1; - return (this.options.dropBufferSupport ? exec : execBuffer).apply(this, arguments); - } - if (!this.nodeifiedPromise) { - this.nodeifiedPromise = true; - standard_as_callback_1.default(this.promise, callback); - } - if (!this._queue.length) { - this.resolve([]); - } - let pipelineSlot; - if (this.isCluster) { - // List of the first key for each command - const sampleKeys = []; - for (let i = 0; i < this._queue.length; i++) { - const keys = this._queue[i].getKeys(); - if (keys.length) { - sampleKeys.push(keys[0]); - } - // For each command, check that the keys belong to the same slot - if (keys.length && calculateSlot.generateMulti(keys) < 0) { - this.reject(new Error("All the keys in a pipeline command should belong to the same slot")); - return this.promise; - } - } - if (sampleKeys.length) { - pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys); - if (pipelineSlot < 0) { - this.reject(new Error("All keys in the pipeline should belong to the same slots allocation group")); - return this.promise; - } - } - else { - // Send the pipeline to a random node - pipelineSlot = (Math.random() * 16384) | 0; - } - } - // Check whether scripts exists - const scripts = []; - for (let i = 0; i < this._queue.length; ++i) { - const item = this._queue[i]; - if (item.name !== "evalsha") { - continue; - } - const script = this._shaToScript[item.args[0]]; - if (!script || this.redis._addedScriptHashes[script.sha]) { - continue; - } - scripts.push(script); - this.redis._addedScriptHashes[script.sha] = true; - } - const _this = this; - if (!scripts.length) { - return execPipeline(); - } - // In cluster mode, always load scripts before running the pipeline - if (this.isCluster) { - return pMap(scripts, (script) => _this.redis.script("load", script.lua), { - concurrency: 10, - }).then(execPipeline); - } - return this.redis - .script("exists", scripts.map(({ sha }) => sha)) - .then(function (results) { - const pending = []; - for (let i = 0; i < results.length; ++i) { - if (!results[i]) { - pending.push(scripts[i]); - } - } - const Promise = PromiseContainer.get(); - return Promise.all(pending.map(function (script) { - return _this.redis.script("load", script.lua); - })); - }) - .then(execPipeline); - function execPipeline() { - let data = ""; - let buffers; - let writePending = (_this.replyPending = _this._queue.length); - let node; - if (_this.isCluster) { - node = { - slot: pipelineSlot, - redis: _this.redis.connectionPool.nodes.all[_this.preferKey], - }; - } - let bufferMode = false; - const stream = { - write: function (writable) { - if (writable instanceof Buffer) { - bufferMode = true; - } - if (bufferMode) { - if (!buffers) { - buffers = []; - } - if (typeof data === "string") { - buffers.push(Buffer.from(data, "utf8")); - data = undefined; - } - buffers.push(typeof writable === "string" - ? Buffer.from(writable, "utf8") - : writable); - } - else { - data += writable; - } - if (!--writePending) { - let sendData; - if (buffers) { - sendData = Buffer.concat(buffers); - } - else { - sendData = data; - } - if (_this.isCluster) { - node.redis.stream.write(sendData); - } - else { - _this.redis.stream.write(sendData); - } - // Reset writePending for resending - writePending = _this._queue.length; - data = ""; - buffers = undefined; - bufferMode = false; - } - }, - }; - for (let i = 0; i < _this._queue.length; ++i) { - _this.redis.sendCommand(_this._queue[i], stream, node); - } - return _this.promise; - } -}; - - -/***/ }), - -/***/ 71475: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isPromise(obj) { - return (!!obj && - (typeof obj === "object" || typeof obj === "function") && - typeof obj.then === "function"); -} -exports.isPromise = isPromise; -let promise = Promise; -function get() { - return promise; -} -exports.get = get; -function set(lib) { - if (typeof lib !== "function") { - throw new Error(`Provided Promise must be a function, got ${lib}`); - } - promise = lib; -} -exports.set = set; - - -/***/ }), - -/***/ 1422: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_REDIS_OPTIONS = { - // Connection - port: 6379, - host: "localhost", - family: 4, - connectTimeout: 10000, - retryStrategy: function (times) { - return Math.min(times * 50, 2000); - }, - keepAlive: 0, - noDelay: true, - connectionName: null, - // Sentinel - sentinels: null, - name: null, - role: "master", - sentinelRetryStrategy: function (times) { - return Math.min(times * 10, 1000); - }, - natMap: null, - enableTLSForSentinelMode: false, - updateSentinels: true, - // Status - username: null, - password: null, - db: 0, - // Others - dropBufferSupport: false, - enableOfflineQueue: true, - enableReadyCheck: true, - autoResubscribe: true, - autoResendUnfulfilledCommands: true, - lazyConnect: false, - keyPrefix: "", - reconnectOnError: null, - readOnly: false, - stringNumbers: false, - maxRetriesPerRequest: 20, - maxLoadingRetryTime: 10000, - enableAutoPipelining: false, - autoPipeliningIgnoredCommands: [], - maxScriptsCachingTime: 60000, -}; - - -/***/ }), - -/***/ 74276: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -const command_1 = __nccwpck_require__(90803); -const errors_1 = __nccwpck_require__(23961); -const utils_1 = __nccwpck_require__(94832); -const DataHandler_1 = __nccwpck_require__(30545); -const debug = utils_1.Debug("connection"); -function connectHandler(self) { - return function () { - self.setStatus("connect"); - self.resetCommandQueue(); - // AUTH command should be processed before any other commands - let flushed = false; - const { connectionEpoch } = self; - if (self.condition.auth) { - self.auth(self.condition.auth, function (err) { - if (connectionEpoch !== self.connectionEpoch) { - return; - } - if (err) { - if (err.message.indexOf("no password is set") !== -1) { - console.warn("[WARN] Redis server does not require a password, but a password was supplied."); - } - else if (err.message.indexOf("without any password configured for the default user") !== -1) { - console.warn("[WARN] This Redis server's `default` user does not require a password, but a password was supplied"); - } - else if (err.message.indexOf("wrong number of arguments for 'auth' command") !== -1) { - console.warn(`[ERROR] The server returned "wrong number of arguments for 'auth' command". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`); - } - else { - flushed = true; - self.recoverFromFatalError(err, err); - } - } - }); - } - if (self.condition.select) { - self.select(self.condition.select); - } - if (!self.options.enableReadyCheck) { - exports.readyHandler(self)(); - } - /* - No need to keep the reference of DataHandler here - because we don't need to do the cleanup. - `Stream#end()` will remove all listeners for us. - */ - new DataHandler_1.default(self, { - stringNumbers: self.options.stringNumbers, - dropBufferSupport: self.options.dropBufferSupport, - }); - if (self.options.enableReadyCheck) { - self._readyCheck(function (err, info) { - if (connectionEpoch !== self.connectionEpoch) { - return; - } - if (err) { - if (!flushed) { - self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err); - } - } - else { - self.serverInfo = info; - if (self.connector.check(info)) { - exports.readyHandler(self)(); - } - else { - self.disconnect(true); - } - } - }); - } - }; -} -exports.connectHandler = connectHandler; -function abortError(command) { - const err = new redis_errors_1.AbortError("Command aborted due to connection close"); - err.command = { - name: command.name, - args: command.args, - }; - return err; -} -// If a contiguous set of pipeline commands starts from index zero then they -// can be safely reattempted. If however we have a chain of pipelined commands -// starting at index 1 or more it means we received a partial response before -// the connection close and those pipelined commands must be aborted. For -// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after -// aborting and purging we'll have a queue that looks like this: [0, 1, 2] -function abortIncompletePipelines(commandQueue) { - let expectedIndex = 0; - for (let i = 0; i < commandQueue.length;) { - const command = commandQueue.peekAt(i).command; - const pipelineIndex = command.pipelineIndex; - if (pipelineIndex === undefined || pipelineIndex === 0) { - expectedIndex = 0; - } - if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - continue; - } - i++; - } -} -// If only a partial transaction result was received before connection close, -// we have to abort any transaction fragments that may have ended up in the -// offline queue -function abortTransactionFragments(commandQueue) { - for (let i = 0; i < commandQueue.length;) { - const command = commandQueue.peekAt(i).command; - if (command.name === "multi") { - break; - } - if (command.name === "exec") { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - break; - } - if (command.inTransaction) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - } - else { - i++; - } - } -} -function closeHandler(self) { - return function () { - self.setStatus("close"); - if (!self.prevCondition) { - self.prevCondition = self.condition; - } - if (self.commandQueue.length) { - abortIncompletePipelines(self.commandQueue); - self.prevCommandQueue = self.commandQueue; - } - if (self.offlineQueue.length) { - abortTransactionFragments(self.offlineQueue); - } - if (self.manuallyClosing) { - self.manuallyClosing = false; - debug("skip reconnecting since the connection is manually closed."); - return close(); - } - if (typeof self.options.retryStrategy !== "function") { - debug("skip reconnecting because `retryStrategy` is not a function"); - return close(); - } - const retryDelay = self.options.retryStrategy(++self.retryAttempts); - if (typeof retryDelay !== "number") { - debug("skip reconnecting because `retryStrategy` doesn't return a number"); - return close(); - } - debug("reconnect in %sms", retryDelay); - self.setStatus("reconnecting", retryDelay); - self.reconnectTimeout = setTimeout(function () { - self.reconnectTimeout = null; - self.connect().catch(utils_1.noop); - }, retryDelay); - const { maxRetriesPerRequest } = self.options; - if (typeof maxRetriesPerRequest === "number") { - if (maxRetriesPerRequest < 0) { - debug("maxRetriesPerRequest is negative, ignoring..."); - } - else { - const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); - if (remainder === 0) { - debug("reach maxRetriesPerRequest limitation, flushing command queue..."); - self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); - } - } - } - }; - function close() { - self.setStatus("end"); - self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - } -} -exports.closeHandler = closeHandler; -function errorHandler(self) { - return function (error) { - debug("error: %s", error); - self.silentEmit("error", error); - }; -} -exports.errorHandler = errorHandler; -function readyHandler(self) { - return function () { - self.setStatus("ready"); - self.retryAttempts = 0; - if (self.options.monitor) { - self.call("monitor"); - const { sendCommand } = self; - self.sendCommand = function (command) { - if (command_1.default.checkFlag("VALID_IN_MONITOR_MODE", command.name)) { - return sendCommand.call(self, command); - } - command.reject(new Error("Connection is in monitoring mode, can't process commands.")); - return command.promise; - }; - self.once("close", function () { - delete self.sendCommand; - }); - self.setStatus("monitoring"); - return; - } - const finalSelect = self.prevCondition - ? self.prevCondition.select - : self.condition.select; - if (self.options.connectionName) { - debug("set the connection name [%s]", self.options.connectionName); - self.client("setname", self.options.connectionName).catch(utils_1.noop); - } - if (self.options.readOnly) { - debug("set the connection to readonly mode"); - self.readonly().catch(utils_1.noop); - } - if (self.prevCondition) { - const condition = self.prevCondition; - self.prevCondition = null; - if (condition.subscriber && self.options.autoResubscribe) { - // We re-select the previous db first since - // `SELECT` command is not valid in sub mode. - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); - } - const subscribeChannels = condition.subscriber.channels("subscribe"); - if (subscribeChannels.length) { - debug("subscribe %d channels", subscribeChannels.length); - self.subscribe(subscribeChannels); - } - const psubscribeChannels = condition.subscriber.channels("psubscribe"); - if (psubscribeChannels.length) { - debug("psubscribe %d channels", psubscribeChannels.length); - self.psubscribe(psubscribeChannels); - } - } - } - if (self.prevCommandQueue) { - if (self.options.autoResendUnfulfilledCommands) { - debug("resend %d unfulfilled commands", self.prevCommandQueue.length); - while (self.prevCommandQueue.length > 0) { - const item = self.prevCommandQueue.shift(); - if (item.select !== self.condition.select && - item.command.name !== "select") { - self.select(item.select); - } - self.sendCommand(item.command, item.stream); - } - } - else { - self.prevCommandQueue = null; - } - } - if (self.offlineQueue.length) { - debug("send %d commands in offline queue", self.offlineQueue.length); - const offlineQueue = self.offlineQueue; - self.resetOfflineQueue(); - while (offlineQueue.length > 0) { - const item = offlineQueue.shift(); - if (item.select !== self.condition.select && - item.command.name !== "select") { - self.select(item.select); - } - self.sendCommand(item.command, item.stream); - } - } - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); - } - }; +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } } -exports.readyHandler = readyHandler; - /***/ }), -/***/ 83609: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41080: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lodash_1 = __nccwpck_require__(20961); -const util_1 = __nccwpck_require__(31669); -const events_1 = __nccwpck_require__(28614); -const Deque = __nccwpck_require__(42342); -const command_1 = __nccwpck_require__(90803); -const commander_1 = __nccwpck_require__(33642); -const utils_1 = __nccwpck_require__(94832); -const standard_as_callback_1 = __nccwpck_require__(91543); -const eventHandler = __nccwpck_require__(74276); -const connectors_1 = __nccwpck_require__(72340); -const ScanStream_1 = __nccwpck_require__(6134); -const commands = __nccwpck_require__(98020); -const PromiseContainer = __nccwpck_require__(71475); -const transaction_1 = __nccwpck_require__(14645); -const RedisOptions_1 = __nccwpck_require__(1422); -const debug = utils_1.Debug("redis"); -/** - * Creates a Redis instance - * - * @constructor - * @param {(number|string|Object)} [port=6379] - Port of the Redis server, - * or a URL string(see the examples below), - * or the `options` object(see the third argument). - * @param {string|Object} [host=localhost] - Host of the Redis server, - * when the first argument is a URL string, - * this argument is an object represents the options. - * @param {Object} [options] - Other options. - * @param {number} [options.port=6379] - Port of the Redis server. - * @param {string} [options.host=localhost] - Host of the Redis server. - * @param {string} [options.family=4] - Version of IP stack. Defaults to 4. - * @param {string} [options.path=null] - Local domain socket path. If set the `port`, - * `host` and `family` will be ignored. - * @param {number} [options.keepAlive=0] - TCP KeepAlive on the socket with a X ms delay before start. - * Set to a non-number value to disable keepAlive. - * @param {boolean} [options.noDelay=true] - Whether to disable the Nagle's Algorithm. By default we disable - * it to reduce the latency. - * @param {string} [options.connectionName=null] - Connection name. - * @param {number} [options.db=0] - Database index to use. - * @param {string} [options.username=null] - If set, client will send AUTH command with this user and password when connected. - * @param {string} [options.password=null] - If set, client will send AUTH command - * with the value of this option when connected. - * @param {boolean} [options.dropBufferSupport=false] - Drop the buffer support for better performance. - * This option is recommended to be enabled when - * handling large array response and you don't need the buffer support. - * @param {boolean} [options.enableReadyCheck=true] - When a connection is established to - * the Redis server, the server might still be loading the database from disk. - * While loading, the server not respond to any commands. - * To work around this, when this option is `true`, - * ioredis will check the status of the Redis server, - * and when the Redis server is able to process commands, - * a `ready` event will be emitted. - * @param {boolean} [options.enableOfflineQueue=true] - By default, - * if there is no active connection to the Redis server, - * commands are added to a queue and are executed once the connection is "ready" - * (when `enableReadyCheck` is `true`, - * "ready" means the Redis server has loaded the database from disk, otherwise means the connection - * to the Redis server has been established). If this option is false, - * when execute the command when the connection isn't ready, an error will be returned. - * @param {number} [options.connectTimeout=10000] - The milliseconds before a timeout occurs during the initial - * connection to the Redis server. - * @param {boolean} [options.autoResubscribe=true] - After reconnected, if the previous connection was in the - * subscriber mode, client will auto re-subscribe these channels. - * @param {boolean} [options.autoResendUnfulfilledCommands=true] - If true, client will resend unfulfilled - * commands(e.g. block commands) in the previous connection when reconnected. - * @param {boolean} [options.lazyConnect=false] - By default, - * When a new `Redis` instance is created, it will connect to Redis server automatically. - * If you want to keep the instance disconnected until a command is called, you can pass the `lazyConnect` option to - * the constructor: - * - * ```javascript - * var redis = new Redis({ lazyConnect: true }); - * // No attempting to connect to the Redis server here. - * // Now let's connect to the Redis server - * redis.get('foo', function () { - * }); - * ``` - * @param {Object} [options.tls] - TLS connection support. See https://github.com/luin/ioredis#tls-options - * @param {string} [options.keyPrefix=''] - The prefix to prepend to all keys in a command. - * @param {function} [options.retryStrategy] - See "Quick Start" section - * @param {number} [options.maxRetriesPerRequest] - See "Quick Start" section - * @param {number} [options.maxLoadingRetryTime=10000] - when redis server is not ready, we will wait for - * `loading_eta_seconds` from `info` command or maxLoadingRetryTime (milliseconds), whichever is smaller. - * @param {function} [options.reconnectOnError] - See "Quick Start" section - * @param {boolean} [options.readOnly=false] - Enable READONLY mode for the connection. - * Only available for cluster mode. - * @param {boolean} [options.stringNumbers=false] - Force numbers to be always returned as JavaScript - * strings. This option is necessary when dealing with big numbers (exceed the [-2^53, +2^53] range). - * @param {boolean} [options.enableTLSForSentinelMode=false] - Whether to support the `tls` option - * when connecting to Redis via sentinel mode. - * @param {NatMap} [options.natMap=null] NAT map for sentinel connector. - * @param {boolean} [options.updateSentinels=true] - Update the given `sentinels` list with new IP - * addresses when communicating with existing sentinels. -* @param {boolean} [options.enableAutoPipelining=false] - When enabled, all commands issued during an event loop - * iteration are automatically wrapped in a pipeline and sent to the server at the same time. - * This can dramatically improve performance. - * @param {string[]} [options.autoPipeliningIgnoredCommands=[]] - The list of commands which must not be automatically wrapped in pipelines. - * @param {number} [options.maxScriptsCachingTime=60000] Default script definition caching time. - * @extends [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) - * @extends Commander - * @example - * ```js - * var Redis = require('ioredis'); - * - * var redis = new Redis(); - * - * var redisOnPort6380 = new Redis(6380); - * var anotherRedis = new Redis(6380, '192.168.100.1'); - * var unixSocketRedis = new Redis({ path: '/tmp/echo.sock' }); - * var unixSocketRedis2 = new Redis('/tmp/echo.sock'); - * var urlRedis = new Redis('redis://user:password@redis-service.com:6379/'); - * var urlRedis2 = new Redis('//localhost:6379'); - * var urlRedisTls = new Redis('rediss://user:password@redis-service.com:6379/'); - * var authedRedis = new Redis(6380, '192.168.100.1', { password: 'password' }); - * ``` - */ -exports.default = Redis; -function Redis() { - if (!(this instanceof Redis)) { - console.error(new Error("Calling `Redis()` like a function is deprecated. Using `new Redis()` instead.").stack.replace("Error", "Warning")); - return new Redis(arguments[0], arguments[1], arguments[2]); - } - this.parseOptions(arguments[0], arguments[1], arguments[2]); - events_1.EventEmitter.call(this); - commander_1.default.call(this); - this.resetCommandQueue(); - this.resetOfflineQueue(); - this.connectionEpoch = 0; - if (this.options.Connector) { - this.connector = new this.options.Connector(this.options); - } - else if (this.options.sentinels) { - this.connector = new connectors_1.SentinelConnector(this.options); - } - else { - this.connector = new connectors_1.StandaloneConnector(this.options); - } - this.retryAttempts = 0; - // Prepare a cache of scripts and setup a interval which regularly clears it - this._addedScriptHashes = {}; - // Prepare autopipelines structures - this._autoPipelines = new Map(); - this._runningAutoPipelines = new Set(); - Object.defineProperty(this, "autoPipelineQueueSize", { - get() { - let queued = 0; - for (const pipeline of this._autoPipelines.values()) { - queued += pipeline.length; - } - return queued; - }, - }); - // end(or wait) -> connecting -> connect -> ready -> end - if (this.options.lazyConnect) { - this.setStatus("wait"); - } - else { - this.connect().catch(lodash_1.noop); - } -} -util_1.inherits(Redis, events_1.EventEmitter); -Object.assign(Redis.prototype, commander_1.default.prototype); -/** - * Create a Redis instance - * - * @deprecated - */ -// @ts-ignore -Redis.createClient = function (...args) { - // @ts-ignore - return new Redis(...args); -}; -/** - * Default options - * - * @var defaultOptions - * @private - */ -Redis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS; -Redis.prototype.resetCommandQueue = function () { - this.commandQueue = new Deque(); -}; -Redis.prototype.resetOfflineQueue = function () { - this.offlineQueue = new Deque(); -}; -Redis.prototype.parseOptions = function () { - this.options = {}; - let isTls = false; - for (let i = 0; i < arguments.length; ++i) { - const arg = arguments[i]; - if (arg === null || typeof arg === "undefined") { - continue; - } - if (typeof arg === "object") { - lodash_1.defaults(this.options, arg); - } - else if (typeof arg === "string") { - lodash_1.defaults(this.options, utils_1.parseURL(arg)); - if (arg.startsWith("rediss://")) { - isTls = true; - } - } - else if (typeof arg === "number") { - this.options.port = arg; - } - else { - throw new Error("Invalid argument " + arg); - } - } - if (isTls) { - lodash_1.defaults(this.options, { tls: true }); - } - lodash_1.defaults(this.options, Redis.defaultOptions); - if (typeof this.options.port === "string") { - this.options.port = parseInt(this.options.port, 10); - } - if (typeof this.options.db === "string") { - this.options.db = parseInt(this.options.db, 10); - } - if (this.options.parser === "hiredis") { - console.warn("Hiredis parser is abandoned since ioredis v3.0, and JavaScript parser will be used"); - } -}; -/** - * Change instance's status - * @private - */ -Redis.prototype.setStatus = function (status, arg) { - // @ts-ignore - if (debug.enabled) { - debug("status[%s]: %s -> %s", this._getDescription(), this.status || "[empty]", status); - } - this.status = status; - process.nextTick(this.emit.bind(this, status, arg)); -}; -/** - * Create a connection to Redis. - * This method will be invoked automatically when creating a new Redis instance - * unless `lazyConnect: true` is passed. - * - * When calling this method manually, a Promise is returned, which will - * be resolved when the connection status is ready. - * @param {function} [callback] - * @return {Promise} - * @public - */ -Redis.prototype.connect = function (callback) { - const _Promise = PromiseContainer.get(); - const promise = new _Promise((resolve, reject) => { - if (this.status === "connecting" || - this.status === "connect" || - this.status === "ready") { - reject(new Error("Redis is already connecting/connected")); - return; - } - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = setInterval(() => { - this._addedScriptHashes = {}; - }, this.options.maxScriptsCachingTime); - this.connectionEpoch += 1; - this.setStatus("connecting"); - const { options } = this; - this.condition = { - select: options.db, - auth: options.username - ? [options.username, options.password] - : options.password, - subscriber: false, - }; - const _this = this; - standard_as_callback_1.default(this.connector.connect(function (type, err) { - _this.silentEmit(type, err); - }), function (err, stream) { - if (err) { - _this.flushQueue(err); - _this.silentEmit("error", err); - reject(err); - _this.setStatus("end"); - return; - } - let CONNECT_EVENT = options.tls ? "secureConnect" : "connect"; - if (options.sentinels && !options.enableTLSForSentinelMode) { - CONNECT_EVENT = "connect"; - } - _this.stream = stream; - if (typeof options.keepAlive === "number") { - stream.setKeepAlive(true, options.keepAlive); - } - if (stream.connecting) { - stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); - if (options.connectTimeout) { - /* - * Typically, Socket#setTimeout(0) will clear the timer - * set before. However, in some platforms (Electron 3.x~4.x), - * the timer will not be cleared. So we introduce a variable here. - * - * See https://github.com/electron/electron/issues/14915 - */ - let connectTimeoutCleared = false; - stream.setTimeout(options.connectTimeout, function () { - if (connectTimeoutCleared) { - return; - } - stream.setTimeout(0); - stream.destroy(); - const err = new Error("connect ETIMEDOUT"); - // @ts-ignore - err.errorno = "ETIMEDOUT"; - // @ts-ignore - err.code = "ETIMEDOUT"; - // @ts-ignore - err.syscall = "connect"; - eventHandler.errorHandler(_this)(err); - }); - stream.once(CONNECT_EVENT, function () { - connectTimeoutCleared = true; - stream.setTimeout(0); - }); - } - } - else { - process.nextTick(eventHandler.connectHandler(_this)); - } - stream.once("error", eventHandler.errorHandler(_this)); - stream.once("close", eventHandler.closeHandler(_this)); - if (options.noDelay) { - stream.setNoDelay(true); - } - const connectionReadyHandler = function () { - _this.removeListener("close", connectionCloseHandler); - resolve(); - }; - var connectionCloseHandler = function () { - _this.removeListener("ready", connectionReadyHandler); - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - }; - _this.once("ready", connectionReadyHandler); - _this.once("close", connectionCloseHandler); - }); - }); - return standard_as_callback_1.default(promise, callback); +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", }; -/** - * Disconnect from Redis. - * - * This method closes the connection immediately, - * and may lose some pending replies that haven't written to client. - * If you want to wait for the pending replies, use Redis#quit instead. - * @public - */ -Redis.prototype.disconnect = function (reconnect) { - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - if (!reconnect) { - this.manuallyClosing = true; - } - if (this.reconnectTimeout && !reconnect) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; - } - if (this.status === "wait") { - eventHandler.closeHandler(this)(); + + + +/***/ }), + +/***/ 11155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +var Buffer = __nccwpck_require__(15118).Buffer; + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; } - else { - this.connector.disconnect(); + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; } -}; -/** - * Disconnect from Redis. - * - * @deprecated - */ -Redis.prototype.end = function () { - this.disconnect(); -}; -/** - * Create a new instance with the same options as the current one. - * - * @example - * ```js - * var redis = new Redis(6380); - * var anotherRedis = redis.duplicate(); - * ``` - * - * @public - */ -Redis.prototype.duplicate = function (override) { - return new Redis(Object.assign({}, this.options, override || {})); -}; -Redis.prototype.recoverFromFatalError = function (commandError, err, options) { - this.flushQueue(err, options); - this.silentEmit("error", err); - this.disconnect(true); -}; -Redis.prototype.handleReconnection = function handleReconnection(err, item) { - let needReconnect = false; - if (this.options.reconnectOnError) { - needReconnect = this.options.reconnectOnError(err); + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; } - switch (needReconnect) { - case 1: - case true: - if (this.status !== "reconnecting") { - this.disconnect(true); - } - item.command.reject(err); - break; - case 2: - if (this.status !== "reconnecting") { - this.disconnect(true); - } - if (this.condition.select !== item.select && - item.command.name !== "select") { - this.select(item.select); - } - this.sendCommand(item.command); - break; - default: - item.command.reject(err); + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; } -}; -/** - * Flush offline queue and command queue with error. - * - * @param {Error} error - The error object to send to the commands - * @param {object} options - * @private - */ -Redis.prototype.flushQueue = function (error, options) { - options = lodash_1.defaults({}, options, { - offlineQueue: true, - commandQueue: true, - }); - let item; - if (options.offlineQueue) { - while (this.offlineQueue.length > 0) { - item = this.offlineQueue.shift(); - item.command.reject(error); - } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; } - if (options.commandQueue) { - if (this.commandQueue.length > 0) { - if (this.stream) { - this.stream.removeAllListeners("data"); - } - while (this.commandQueue.length > 0) { - item = this.commandQueue.shift(); - item.command.reject(error); + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; } } + + return enc; +} + + + + +/***/ }), + +/***/ 51644: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +var Buffer = __nccwpck_require__(15118).Buffer; + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; }; -/** - * Check whether Redis has finished loading the persistent data and is able to - * process commands. - * - * @param {Function} callback - * @private - */ -Redis.prototype._readyCheck = function (callback) { - const _this = this; - this.info(function (err, res) { - if (err) { - return callback(err); - } - if (typeof res !== "string") { - return callback(null, res); - } - const info = {}; - const lines = res.split("\r\n"); - for (let i = 0; i < lines.length; ++i) { - const [fieldName, ...fieldValueParts] = lines[i].split(":"); - const fieldValue = fieldValueParts.join(":"); - if (fieldValue) { - info[fieldName] = fieldValue; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; } - } - if (!info.loading || info.loading === "0") { - callback(null, info); - } - else { - const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000; - const retryTime = _this.options.maxLoadingRetryTime && - _this.options.maxLoadingRetryTime < loadingEtaMs - ? _this.options.maxLoadingRetryTime - : loadingEtaMs; - debug("Redis server still loading, trying again in " + retryTime + "ms"); - setTimeout(function () { - _this._readyCheck(callback); - }, retryTime); - } - }); -}; -/** - * Emit only when there's at least one listener. - * - * @param {string} eventName - Event to emit - * @param {...*} arguments - Arguments - * @return {boolean} Returns true if event had listeners, false otherwise. - * @private - */ -Redis.prototype.silentEmit = function (eventName) { - let error; - if (eventName === "error") { - error = arguments[1]; - if (this.status === "end") { - return; - } - if (this.manuallyClosing) { - // ignore connection related errors when manually disconnecting - if (error instanceof Error && - (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG || - // @ts-ignore - error.syscall === "connect" || - // @ts-ignore - error.syscall === "read")) { - return; + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; } } } - if (this.listeners(eventName).length > 0) { - return this.emit.apply(this, arguments); - } - if (error && error instanceof Error) { - console.error("[ioredis] Unhandled error event:", error.stack); + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } - return false; -}; -/** - * Listen for all requests received by the server in real time. - * - * This command will create a new connection to Redis and send a - * MONITOR command via the new connection in order to avoid disturbing - * the current connection. - * - * @param {function} [callback] The callback function. If omit, a promise will be returned. - * @example - * ```js - * var redis = new Redis(); - * redis.monitor(function (err, monitor) { - * // Entering monitoring mode. - * monitor.on('monitor', function (time, args, source, database) { - * console.log(time + ": " + util.inspect(args)); - * }); - * }); - * - * // supports promise as well as other commands - * redis.monitor().then(function (monitor) { - * monitor.on('monitor', function (time, args, source, database) { - * console.log(time + ": " + util.inspect(args)); - * }); - * }); - * ``` - * @public - */ -Redis.prototype.monitor = function (callback) { - const monitorInstance = this.duplicate({ - monitor: true, - lazyConnect: false, - }); - const Promise = PromiseContainer.get(); - return standard_as_callback_1.default(new Promise(function (resolve) { - monitorInstance.once("monitoring", function () { - resolve(monitorInstance); - }); - }), callback); + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; }; -transaction_1.addTransactionSupport(Redis.prototype); -/** - * Send a command to Redis - * - * This method is used internally by the `Redis#set`, `Redis#lpush` etc. - * Most of the time you won't invoke this method directly. - * However when you want to send a command that is not supported by ioredis yet, - * this command will be useful. - * - * @method sendCommand - * @memberOf Redis# - * @param {Command} command - The Command instance to send. - * @see {@link Command} - * @example - * ```js - * var redis = new Redis(); - * - * // Use callback - * var get = new Command('get', ['foo'], 'utf8', function (err, result) { - * console.log(result); - * }); - * redis.sendCommand(get); - * - * // Use promise - * var set = new Command('set', ['foo', 'bar'], 'utf8'); - * set.promise.then(function (result) { - * console.log(result); - * }); - * redis.sendCommand(set); - * ``` - * @private - */ -Redis.prototype.sendCommand = function (command, stream) { - if (this.status === "wait") { - this.connect().catch(lodash_1.noop); - } - if (this.status === "end") { - command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return command.promise; - } - if (this.condition.subscriber && - !command_1.default.checkFlag("VALID_IN_SUBSCRIBER_MODE", command.name)) { - command.reject(new Error("Connection in subscriber mode, only subscriber commands may be used")); - return command.promise; - } - if (command.name === "quit") { - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - } - let writable = this.status === "ready" || - (!stream && - this.status === "connect" && - commands.exists(command.name) && - commands.hasFlag(command.name, "loading")); - if (!this.stream) { - writable = false; - } - else if (!this.stream.writable) { - writable = false; - } - else if (this.stream._writableState && this.stream._writableState.ended) { - // https://github.com/iojs/io.js/pull/1217 - writable = false; - } - if (!writable && !this.options.enableOfflineQueue) { - command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); - return command.promise; - } - if (!writable && command.name === "quit" && this.offlineQueue.length === 0) { - this.disconnect(); - command.resolve(Buffer.from("OK")); - return command.promise; - } - if (writable) { - // @ts-ignore - if (debug.enabled) { - debug("write command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); - } - (stream || this.stream).write(command.toWritable()); - this.commandQueue.push({ - command: command, - stream: stream, - select: this.condition.select, - }); - if (command_1.default.checkFlag("WILL_DISCONNECT", command.name)) { - this.manuallyClosing = true; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } } } - else if (this.options.enableOfflineQueue) { - // @ts-ignore - if (debug.enabled) { - debug("queue command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; } - this.offlineQueue.push({ - command: command, - stream: stream, - select: this.condition.select, - }); + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; } - if (command.name === "select" && utils_1.isInt(command.args[0])) { - const db = parseInt(command.args[0], 10); - if (this.condition.select !== db) { - this.condition.select = db; - this.emit("select", db); - debug("switch to db [%d]", this.condition.select); + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } } } - return command.promise; -}; -/** - * Get description of the connection. Used for debugging. - * @private - */ -Redis.prototype._getDescription = function () { - let description; - if (this.options.path) { - description = this.options.path; - } - else if (this.stream && - this.stream.remoteAddress && - this.stream.remotePort) { - description = this.stream.remoteAddress + ":" + this.stream.remotePort; - } - else { - description = this.options.host + ":" + this.options.port; + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } - if (this.options.connectionName) { - description += ` (${this.options.connectionName})`; + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + + + +/***/ }), + +/***/ 67961: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; } - return description; -}; -[ - "scan", - "sscan", - "hscan", - "zscan", - "scanBuffer", - "sscanBuffer", - "hscanBuffer", - "zscanBuffer", -].forEach(function (command) { - Redis.prototype[command + "Stream"] = function (key, options) { - if (command === "scan" || command === "scanBuffer") { - options = key; - key = null; - } - return new ScanStream_1.default(lodash_1.defaults({ - objectMode: true, - key: key, - redis: this, - command: command, - }, options)); - }; -}); + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + /***/ }), -/***/ 88540: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 30393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const crypto_1 = __nccwpck_require__(76417); -const promiseContainer_1 = __nccwpck_require__(71475); -const command_1 = __nccwpck_require__(90803); -const standard_as_callback_1 = __nccwpck_require__(91543); -class Script { - constructor(lua, numberOfKeys = null, keyPrefix = "", readOnly = false) { - this.lua = lua; - this.numberOfKeys = numberOfKeys; - this.keyPrefix = keyPrefix; - this.readOnly = readOnly; - this.sha = crypto_1.createHash("sha1").update(lua).digest("hex"); - } - execute(container, args, options, callback) { - if (typeof this.numberOfKeys === "number") { - args.unshift(this.numberOfKeys); - } - if (this.keyPrefix) { - options.keyPrefix = this.keyPrefix; +var Buffer = __nccwpck_require__(64293).Buffer; +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; } - if (this.readOnly) { - options.readOnly = true; + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; } - const evalsha = new command_1.default("evalsha", [this.sha].concat(args), options); - evalsha.isCustomCommand = true; - const result = container.sendCommand(evalsha); - if (promiseContainer_1.isPromise(result)) { - return standard_as_callback_1.default(result.catch((err) => { - if (err.toString().indexOf("NOSCRIPT") === -1) { - throw err; - } - return container.sendCommand(new command_1.default("eval", [this.lua].concat(args), options)); - }), callback); + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); } - // result is not a Promise--probably returned from a pipeline chain; however, - // we still need the callback to fire when the script is evaluated - standard_as_callback_1.default(evalsha.promise, callback); - return result; - } -} -exports.default = Script; + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } -/***/ }), + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); -/***/ 14645: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); -"use strict"; + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const standard_as_callback_1 = __nccwpck_require__(91543); -const pipeline_1 = __nccwpck_require__(42803); -function addTransactionSupport(redis) { - redis.pipeline = function (commands) { - const pipeline = new pipeline_1.default(this); - if (Array.isArray(commands)) { - pipeline.addBatch(commands); + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; } - return pipeline; - }; - const { multi } = redis; - redis.multi = function (commands, options) { - if (typeof options === "undefined" && !Array.isArray(commands)) { - options = commands; - commands = null; + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); } - if (options && options.pipeline === false) { - return multi.call(this); + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; } - const pipeline = new pipeline_1.default(this); - pipeline.multi(); - if (Array.isArray(commands)) { - pipeline.addBatch(commands); + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); } - const exec = pipeline.exec; - pipeline.exec = function (callback) { - // Wait for the cluster to be connected, since we need nodes information before continuing - if (this.isCluster && !this.redis.slots.length) { - return standard_as_callback_1.default(new Promise((resolve, reject) => { - this.redis.delayUntilReady((err) => { - if (err) { - reject(err); - return; - } - this.exec(pipeline).then(resolve, reject); - }); - }), callback); - } - if (this._transactions > 0) { - exec.call(pipeline); - } - // Returns directly when the pipeline - // has been called multiple times (retries). - if (this.nodeifiedPromise) { - return exec.call(pipeline); - } - const promise = exec.call(pipeline); - return standard_as_callback_1.default(promise.then(function (result) { - const execResult = result[result.length - 1]; - if (typeof execResult === "undefined") { - throw new Error("Pipeline cannot be used to send any commands when the `exec()` has been called on it."); + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; } - if (execResult[0]) { - execResult[0].previousErrors = []; - for (let i = 0; i < result.length - 1; ++i) { - if (result[i][0]) { - execResult[0].previousErrors.push(result[i][0]); - } - } - throw execResult[0]; + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; } - return utils_1.wrapMultiResult(execResult[1]); - }), callback); - }; - const { execBuffer } = pipeline; - pipeline.execBuffer = function (callback) { - if (this._transactions > 0) { - execBuffer.call(pipeline); } - return pipeline.exec(callback); - }; - return pipeline; - }; - const { exec } = redis; - redis.exec = function (callback) { - return standard_as_callback_1.default(exec.call(this).then(function (results) { - if (Array.isArray(results)) { - results = utils_1.wrapMultiResult(results); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = __nccwpck_require__(92413).Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; } - return results; - }), callback); - }; + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = __nccwpck_require__(92413).Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } } -exports.addTransactionSupport = addTransactionSupport; /***/ }), -/***/ 85356: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 19032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __nccwpck_require__(38237); -const MAX_ARGUMENT_LENGTH = 200; -exports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH; -const NAMESPACE_PREFIX = "ioredis"; -/** - * helper function that tried to get a string value for - * arbitrary "debug" arg - */ -function getStringValue(v) { - if (v === null) { - return; - } - switch (typeof v) { - case "boolean": - return; - case "number": - return; - case "object": - if (Buffer.isBuffer(v)) { - return v.toString("hex"); - } - if (Array.isArray(v)) { - return v.join(","); - } - try { - return JSON.stringify(v); - } - catch (e) { - return; - } - case "string": - return v; + +// Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. +var Buffer = __nccwpck_require__(15118).Buffer; + +var bomHandling = __nccwpck_require__(67961), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; } -exports.getStringValue = getStringValue; -/** - * helper function that redacts a string representation of a "debug" arg - */ -function genRedactedString(str, maxLen) { - const { length } = str; - return length <= maxLen - ? str - : str.slice(0, maxLen) + ' ... '; + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } } -exports.genRedactedString = genRedactedString; -/** - * a wrapper for the `debug` module, used to generate - * "debug functions" that trim the values in their output - */ -function genDebugFunction(namespace) { - const fn = debug_1.default(`${NAMESPACE_PREFIX}:${namespace}`); - function wrappedDebug(...args) { - if (!fn.enabled) { - return; // no-op - } - // we skip the first arg because that is the message - for (let i = 1; i < args.length; i++) { - const str = getStringValue(args[i]); - if (typeof str === "string" && str.length > MAX_ARGUMENT_LENGTH) { - args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH); - } + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } - return fn.apply(null, args); } - Object.defineProperties(wrappedDebug, { - namespace: { - get() { - return fn.namespace; - }, - }, - enabled: { - get() { - return fn.enabled; - }, - }, - destroy: { - get() { - return fn.destroy; - }, - }, - log: { - get() { - return fn.log; - }, - set(l) { - fn.log = l; - }, - }, - }); - return wrappedDebug; } -exports.default = genDebugFunction; + +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + __nccwpck_require__(76409)(iconv); + } + + // Load Node primitive extensions. + __nccwpck_require__(30393)(iconv); +} + +if (false) {} /***/ }), -/***/ 94832: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 76409: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const url_1 = __nccwpck_require__(78835); -const lodash_1 = __nccwpck_require__(20961); -exports.defaults = lodash_1.defaults; -exports.noop = lodash_1.noop; -exports.flatten = lodash_1.flatten; -const debug_1 = __nccwpck_require__(85356); -exports.Debug = debug_1.default; -/** - * Test if two buffers are equal - * - * @export - * @param {Buffer} a - * @param {Buffer} b - * @returns {boolean} Whether the two buffers are equal - */ -function bufferEqual(a, b) { - if (typeof a.equals === "function") { - return a.equals(b); - } - if (a.length !== b.length) { - return false; - } - for (let i = 0; i < a.length; ++i) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -} -exports.bufferEqual = bufferEqual; -/** - * Convert a buffer to string, supports buffer array - * - * @param {*} value - The input value - * @param {string} encoding - string encoding - * @return {*} The result - * @example - * ```js - * var input = [Buffer.from('foo'), [Buffer.from('bar')]] - * var res = convertBufferToString(input, 'utf8') - * expect(res).to.eql(['foo', ['bar']]) - * ``` - * @private - */ -function convertBufferToString(value, encoding) { - if (value instanceof Buffer) { - return value.toString(encoding); + +var Buffer = __nccwpck_require__(64293).Buffer, + Transform = __nccwpck_require__(92413).Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } - if (Array.isArray(value)) { - const length = value.length; - const res = Array(length); - for (let i = 0; i < length; ++i) { - res[i] = - value[i] instanceof Buffer && encoding === "utf8" - ? value[i].toString() - : convertBufferToString(value[i], encoding); - } - return res; + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); } - return value; + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); } -exports.convertBufferToString = convertBufferToString; -/** - * Convert a list of results to node-style - * - * @param {Array} arr - The input value - * @return {Array} The output value - * @example - * ```js - * var input = ['a', 'b', new Error('c'), 'd'] - * var output = exports.wrapMultiResult(input) - * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) - * ``` - * @private - */ -function wrapMultiResult(arr) { - // When using WATCH/EXEC transactions, the EXEC will return - // a null instead of an array - if (!arr) { - return null; + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); } - const result = []; - const length = arr.length; - for (let i = 0; i < length; ++i) { - const item = arr[i]; - if (item instanceof Error) { - result.push([item]); - } - else { - result.push([null, item]); - } + catch (e) { + done(e); } - return result; -} -exports.wrapMultiResult = wrapMultiResult; -/** - * Detect the argument is a int - * - * @param {string} value - * @return {boolean} Whether the value is a int - * @example - * ```js - * > isInt('123') - * true - * > isInt('123.3') - * false - * > isInt('1x') - * false - * > isInt(123) - * true - * > isInt(true) - * false - * ``` - * @private - */ -function isInt(value) { - const x = parseFloat(value); - return !isNaN(value) && (x | 0) === x; } -exports.isInt = isInt; -/** - * Pack an array to an Object - * - * @param {array} array - * @return {object} - * @example - * ```js - * > packObject(['a', 'b', 'c', 'd']) - * { a: 'b', c: 'd' } - * ``` - */ -function packObject(array) { - const result = {}; - const length = array.length; - for (let i = 1; i < length; i += 2) { - result[array[i - 1]] = array[i]; + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); } - return result; -} -exports.packObject = packObject; -/** - * Return a callback with timeout - * - * @param {function} callback - * @param {number} timeout - * @return {function} - */ -function timeout(callback, timeout) { - let timer; - const run = function () { - if (timer) { - clearTimeout(timer); - timer = null; - callback.apply(this, arguments); - } - }; - timer = setTimeout(run, timeout, new Error("timeout")); - return run; -} -exports.timeout = timeout; -/** - * Convert an object to an array - * - * @param {object} obj - * @return {array} - * @example - * ```js - * > convertObjectToArray({ a: '1' }) - * ['a', '1'] - * ``` - */ -function convertObjectToArray(obj) { - const result = []; - const keys = Object.keys(obj); - for (let i = 0, l = keys.length; i < l; i++) { - result.push(keys[i], obj[keys[i]]); + catch (e) { + done(e); } - return result; } -exports.convertObjectToArray = convertObjectToArray; -/** - * Convert a map to an array - * - * @param {Map} map - * @return {array} - * @example - * ```js - * > convertObjectToArray(new Map([[1, '2']])) - * [1, '2'] - * ``` - */ -function convertMapToArray(map) { - const result = []; - let pos = 0; - map.forEach(function (value, key) { - result[pos] = key; - result[pos + 1] = value; - pos += 2; + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); }); - return result; + return this; } -exports.convertMapToArray = convertMapToArray; -/** - * Convert a non-string arg to a string - * - * @param {*} arg - * @return {string} - */ -function toArg(arg) { - if (arg === null || typeof arg === "undefined") { - return ""; - } - return String(arg); + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); } -exports.toArg = toArg; -/** - * Optimize error stack - * - * @param {Error} error - actually error - * @param {string} friendlyStack - the stack that more meaningful - * @param {string} filterPath - only show stacks with the specified path - */ -function optimizeErrorStack(error, friendlyStack, filterPath) { - const stacks = friendlyStack.split("\n"); - let lines = ""; - let i; - for (i = 1; i < stacks.length; ++i) { - if (stacks[i].indexOf(filterPath) === -1) { - break; - } + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); } - for (let j = i; j < stacks.length; ++j) { - lines += "\n" + stacks[j]; + catch (e) { + done(e); } - const pos = error.stack.indexOf("\n"); - error.stack = error.stack.slice(0, pos) + lines; - return error; } -exports.optimizeErrorStack = optimizeErrorStack; -/** - * Parse the redis protocol url - * - * @param {string} url - the redis protocol url - * @return {Object} - */ -function parseURL(url) { - if (isInt(url)) { - return { port: url }; - } - let parsed = url_1.parse(url, true, true); - if (!parsed.slashes && url[0] !== "/") { - url = "//" + url; - parsed = url_1.parse(url, true, true); - } - const result = {}; - if (parsed.auth) { - const parsedAuth = parsed.auth.split(":"); - result.password = parsedAuth[1]; - } - if (parsed.pathname) { - if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { - if (parsed.pathname.length > 1) { - result.db = parsed.pathname.slice(1); - } - } - else { - result.path = parsed.pathname; - } - } - if (parsed.host) { - result.host = parsed.hostname; + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); } - if (parsed.port) { - result.port = parsed.port; + catch (e) { + done(e); } - lodash_1.defaults(result, parsed.query); - return result; } -exports.parseURL = parseURL; -/** - * Get a random element from `array` - * - * @export - * @template T - * @param {T[]} array the array - * @param {number} [from=0] start index - * @returns {T} - */ -function sample(array, from = 0) { - const length = array.length; - if (from >= length) { - return; - } - return array[from + Math.floor(Math.random() * (length - from))]; + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; } -exports.sample = sample; -/** - * Shuffle the array using the Fisher-Yates Shuffle. - * This method will mutate the original array. - * - * @export - * @template T - * @param {T[]} array - * @returns {T[]} - */ -function shuffle(array) { - let counter = array.length; - // While there are elements in the array - while (counter > 0) { - // Pick a random index - const index = Math.floor(Math.random() * counter); - // Decrease counter by 1 - counter--; - // And swap the last element with it - [array[counter], array[index]] = [array[index], array[counter]]; - } - return array; + + + +/***/ }), + +/***/ 91230: +/***/ ((module) => { + +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] } -exports.shuffle = shuffle; -/** - * Error message for connection being disconnected - */ -exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; -function zipMap(keys, values) { - const map = new Map(); - keys.forEach((key, index) => { - map.set(key, values[index]); - }); - return map; + +const EMPTY = '' +const SPACE = ' ' +const ESCAPE = '\\' +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ + +const SLASH = '/' +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore' + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +) + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) } -exports.zipMap = zipMap; +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` -/***/ }), +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ -/***/ 20961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? SPACE + : EMPTY + ], -"use strict"; + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE + ], -Object.defineProperty(exports, "__esModule", ({ value: true })); -const defaults = __nccwpck_require__(11289); -exports.defaults = defaults; -const flatten = __nccwpck_require__(48919); -exports.flatten = flatten; -function noop() { } -exports.noop = noop; + // Escape metacharacters + // which is written down by users but means special for regular expressions. + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], -/***/ }), + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], -/***/ 37263: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + // leading slash + [ -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function() { - var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], - ipaddr = {}; + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], - root = this; + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, - if (( true && module !== null) && module.exports) { - module.exports = ipaddr; - } else { - root['ipaddr'] = ipaddr; - } + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], - matchCIDR = function(first, second, partSize, cidrBits) { - var part, shift; - if (first.length !== second.length) { - throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); - } - part = 0; - while (cidrBits > 0) { - shift = partSize - cidrBits; - if (shift < 0) { - shift = 0; - } - if (first[part] >> shift !== second[part] >> shift) { - return false; - } - cidrBits -= partSize; - part += 1; - } - return true; - }; + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern - ipaddr.subnetMatch = function(address, rangeList, defaultName) { - var k, len, rangeName, rangeSubnets, subnet; - if (defaultName == null) { - defaultName = 'unicast'; - } - for (rangeName in rangeList) { - rangeSubnets = rangeList[rangeName]; - if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { - rangeSubnets = [rangeSubnets]; - } - for (k = 0, len = rangeSubnets.length; k < len; k++) { - subnet = rangeSubnets[k]; - if (address.kind() === subnet[0].kind()) { - if (address.match.apply(address, subnet)) { - return rangeName; - } - } - } - } - return defaultName; - }; + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' - ipaddr.IPv4 = (function() { - function IPv4(octets) { - var k, len, octet; - if (octets.length !== 4) { - throw new Error("ipaddr: ipv4 octet count should be 4"); - } - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); - } - } - this.octets = octets; + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' } + ], - IPv4.prototype.kind = function() { - return 'ipv4'; - }; + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, - IPv4.prototype.toString = function() { - return this.octets.join("."); - }; + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer - IPv4.prototype.toNormalizedString = function() { - return this.toString(); - }; + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length - IPv4.prototype.toByteArray = function() { - return this.octets.slice(0); - }; + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' - IPv4.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv4') { - throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); - } - return matchCIDR(this.octets, other.octets, 8, cidrRange); - }; + // case: /** + // > A trailing `"/**"` matches everything inside. - IPv4.prototype.SpecialRanges = { - unspecified: [[new IPv4([0, 0, 0, 0]), 8]], - broadcast: [[new IPv4([255, 255, 255, 255]), 32]], - multicast: [[new IPv4([224, 0, 0, 0]), 4]], - linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], - loopback: [[new IPv4([127, 0, 0, 0]), 8]], - carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], - "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], - reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] - }; + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], - IPv4.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' - IPv4.prototype.toIPv4MappedAddress = function() { - return ipaddr.IPv6.parse("::ffff:" + (this.toString())); - }; + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, - IPv4.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, octet, stop, zeros, zerotable; - zerotable = { - 0: 8, - 128: 7, - 192: 6, - 224: 5, - 240: 4, - 248: 3, - 252: 2, - 254: 1, - 255: 0 - }; - cidr = 0; - stop = false; - for (i = k = 3; k >= 0; i = k += -1) { - octet = this.octets[i]; - if (octet in zerotable) { - zeros = zerotable[octet]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 8) { - stop = true; - } - cidr += zeros; - } else { - return null; - } - } - return 32 - cidr; - }; + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], - return IPv4; + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], - })(); + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], - ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. - ipv4Regexes = { - fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), - longValue: new RegExp("^" + ipv4Part + "$", 'i') - }; + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], - ipaddr.IPv4.parser = function(string) { - var match, parseIntAuto, part, shift, value; - parseIntAuto = function(string) { - if (string[0] === "0" && string[1] !== "x") { - return parseInt(string, 8); - } else { - return parseInt(string); - } - }; - if (match = string.match(ipv4Regexes.fourOctet)) { - return (function() { - var k, len, ref, results; - ref = match.slice(1, 6); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseIntAuto(part)); - } - return results; - })(); - } else if (match = string.match(ipv4Regexes.longValue)) { - value = parseIntAuto(match[1]); - if (value > 0xffffffff || value < 0) { - throw new Error("ipaddr: address outside defined range"); - } - return ((function() { - var k, results; - results = []; - for (shift = k = 0; k <= 24; shift = k += 8) { - results.push((value >> shift) & 0xff); - } - return results; - })()).reverse(); - } else { - return null; - } - }; + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, - ipaddr.IPv6 = (function() { - function IPv6(parts, zoneId) { - var i, k, l, len, part, ref; - if (parts.length === 16) { - this.parts = []; - for (i = k = 0; k <= 14; i = k += 2) { - this.parts.push((parts[i] << 8) | parts[i + 1]); - } - } else if (parts.length === 8) { - this.parts = parts; - } else { - throw new Error("ipaddr: ipv6 part count should be 8 or 16"); - } - ref = this.parts; - for (l = 0, len = ref.length; l < len; l++) { - part = ref[l]; - if (!((0 <= part && part <= 0xffff))) { - throw new Error("ipaddr: ipv6 part should fit in 16 bits"); - } - } - if (zoneId) { - this.zoneId = zoneId; - } + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` } + ], +] - IPv6.prototype.kind = function() { - return 'ipv6'; - }; +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null) - IPv6.prototype.toString = function() { - return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); - }; +// @param {pattern} +const makeRegex = (pattern, negative, ignorecase) => { + const r = regexCache[pattern] + if (r) { + return r + } - IPv6.prototype.toRFC5952String = function() { - var bestMatchIndex, bestMatchLength, match, regex, string; - regex = /((^|:)(0(:|$)){2,})/g; - string = this.toNormalizedString(); - bestMatchIndex = 0; - bestMatchLength = -1; - while ((match = regex.exec(string))) { - if (match[0].length > bestMatchLength) { - bestMatchIndex = match.index; - bestMatchLength = match[0].length; - } - } - if (bestMatchLength < 0) { - return string; - } - return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); - }; + // const replacers = negative + // ? NEGATIVE_REPLACERS + // : POSITIVE_REPLACERS - IPv6.prototype.toByteArray = function() { - var bytes, k, len, part, ref; - bytes = []; - ref = this.parts; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - bytes.push(part >> 8); - bytes.push(part & 0xff); - } - return bytes; - }; + const source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ) - IPv6.prototype.toNormalizedString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16)); - } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; - }; + return regexCache[pattern] = ignorecase + ? new RegExp(source, 'i') + : new RegExp(source) +} + +const isString = subject => typeof subject === 'string' + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 - IPv6.prototype.toFixedLengthString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16).padStart(4, '0')); - } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; - }; +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) - IPv6.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv6') { - throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); - } - return matchCIDR(this.parts, other.parts, 16, cidrRange); - }; +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex + } +} - IPv6.prototype.SpecialRanges = { - unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], - linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], - multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], - loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], - uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], - ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], - rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], - rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], - '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], - teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], - reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] - }; +const createRule = (pattern, ignorecase) => { + const origin = pattern + let negative = false - IPv6.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } - IPv6.prototype.isIPv4MappedAddress = function() { - return this.range() === 'ipv4Mapped'; - }; + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') - IPv6.prototype.toIPv4Address = function() { - var high, low, ref; - if (!this.isIPv4MappedAddress()) { - throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); - } - ref = this.parts.slice(-2), high = ref[0], low = ref[1]; - return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); - }; + const regex = makeRegex(pattern, negative, ignorecase) - IPv6.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, part, stop, zeros, zerotable; - zerotable = { - 0: 16, - 32768: 15, - 49152: 14, - 57344: 13, - 61440: 12, - 63488: 11, - 64512: 10, - 65024: 9, - 65280: 8, - 65408: 7, - 65472: 6, - 65504: 5, - 65520: 4, - 65528: 3, - 65532: 2, - 65534: 1, - 65535: 0 - }; - cidr = 0; - stop = false; - for (i = k = 7; k >= 0; i = k += -1) { - part = this.parts[i]; - if (part in zerotable) { - zeros = zerotable[part]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 16) { - stop = true; - } - cidr += zeros; - } else { - return null; - } - } - return 128 - cidr; - }; + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} - return IPv6; +const throwError = (message, Ctor) => { + throw new Ctor(message) +} - })(); +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } - ipv6Part = "(?:[0-9a-f]+::?)+"; + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } - zoneIndex = "%[0-9a-z]{1,}"; + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } - ipv6Regexes = { - zoneIndex: new RegExp(zoneIndex, 'i'), - "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), - transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') - }; + return true +} - expandIPv6 = function(string, parts) { - var colonCount, lastColon, part, replacement, replacementCount, zoneId; - if (string.indexOf('::') !== string.lastIndexOf('::')) { - return null; - } - zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; - if (zoneId) { - zoneId = zoneId.substring(1); - string = string.replace(/%.+$/, ''); - } - colonCount = 0; - lastColon = -1; - while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { - colonCount++; - } - if (string.substr(0, 2) === '::') { - colonCount--; - } - if (string.substr(-2, 2) === '::') { - colonCount--; - } - if (colonCount > parts) { - return null; - } - replacementCount = parts - colonCount; - replacement = ':'; - while (replacementCount--) { - replacement += '0:'; - } - string = string.replace('::', replacement); - if (string[0] === ':') { - string = string.slice(1); - } - if (string[string.length - 1] === ':') { - string = string.slice(0, -1); - } - parts = (function() { - var k, len, ref, results; - ref = string.split(":"); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseInt(part, 16)); - } - return results; - })(); - return { - parts: parts, - zoneId: zoneId - }; - }; +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) - ipaddr.IPv6.parser = function(string) { - var addr, k, len, match, octet, octets, zoneId; - if (ipv6Regexes['native'].test(string)) { - return expandIPv6(string, 8); - } else if (match = string.match(ipv6Regexes['transitional'])) { - zoneId = match[6] || ''; - addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); - if (addr.parts) { - octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - return null; - } - } - addr.parts.push(octets[0] << 8 | octets[1]); - addr.parts.push(octets[2] << 8 | octets[3]); - return { - parts: addr.parts, - zoneId: addr.zoneId - }; - } - } - return null; - }; +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p - ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { - return this.parser(string) !== null; - }; +class Ignore { + constructor ({ + ignorecase = true + } = {}) { + this._rules = [] + this._ignorecase = ignorecase + define(this, KEY_IGNORE, true) + this._initCache() + } - ipaddr.IPv4.isValid = function(string) { - var e; - try { - new this(this.parser(string)); - return true; - } catch (error1) { - e = error1; - return false; - } - }; + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } - ipaddr.IPv4.isValidFourPartDecimal = function(string) { - if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { - return true; - } else { - return false; + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return } - }; - ipaddr.IPv6.isValid = function(string) { - var addr, e; - if (typeof string === "string" && string.indexOf(":") === -1) { - return false; - } - try { - addr = this.parser(string); - new this(addr.parts, addr.zoneId); - return true; - } catch (error1) { - e = error1; - return false; + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase) + this._added = true + this._rules.push(rule) } - }; + } - ipaddr.IPv4.parse = function(string) { - var parts; - parts = this.parser(string); - if (parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); - } - return new this(parts); - }; + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false - ipaddr.IPv6.parse = function(string) { - var addr; - addr = this.parser(string); - if (addr.parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); - } - return new this(addr.parts, addr.zoneId); - }; + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) - ipaddr.IPv4.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 32) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() } - throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); - }; - ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { - var filledOctetCount, j, octets; - prefix = parseInt(prefix); - if (prefix < 0 || prefix > 32) { - throw new Error('ipaddr: invalid IPv4 prefix length'); - } - octets = [0, 0, 0, 0]; - j = 0; - filledOctetCount = Math.floor(prefix / 8); - while (j < filledOctetCount) { - octets[j] = 255; - j++; - } - if (filledOctetCount < 4) { - octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); - } - return new this(octets); - }; + return this + } - ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); - } - }; + // legacy + addPattern (pattern) { + return this.add(pattern) + } - ipaddr.IPv4.networkAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); - } - }; + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X - ipaddr.IPv6.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 128) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } - } - throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); - }; + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen - ipaddr.isValid = function(string) { - return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); - }; + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. - ipaddr.parse = function(string) { - if (ipaddr.IPv6.isValid(string)) { - return ipaddr.IPv6.parse(string); - } else if (ipaddr.IPv4.isValid(string)) { - return ipaddr.IPv4.parse(string); - } else { - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); - } - }; + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false - ipaddr.parseCIDR = function(string) { - var e; - try { - return ipaddr.IPv6.parseCIDR(string); - } catch (error1) { - e = error1; - try { - return ipaddr.IPv4.parseCIDR(string); - } catch (error1) { - e = error1; - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return } - } - }; - ipaddr.fromByteArray = function(bytes) { - var length; - length = bytes.length; - if (length === 4) { - return new ipaddr.IPv4(bytes); - } else if (length === 16) { - return new ipaddr.IPv6(bytes); - } else { - throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); - } - }; + const matched = rule.regex.test(path) - ipaddr.process = function(string) { - var addr; - addr = this.parse(string); - if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { - return addr.toIPv4Address(); - } else { - return addr; + if (matched) { + ignored = !negative + unignored = negative + } + }) + + return { + ignored, + unignored } - }; + } -}).call(this); + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + + checkPath(path, originalPath, throwError) + + return this._t(path, cache, checkUnignored, slices) + } + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } -/***/ }), + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } -/***/ 7604: -/***/ ((module) => { + slices.pop() -"use strict"; + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); -}; + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + createFilter () { + return path => !this.ignores(path) + } -/***/ }), + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } -/***/ 31310: -/***/ (function(module, exports) { + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} -;(function(root) { - 'use strict'; +const factory = options => new Ignore(options) - function isBase64(v, opts) { - if (v instanceof Boolean || typeof v === 'boolean') { - return false - } +const returnFalse = () => false - if (!(opts instanceof Object)) { - opts = {} - } +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, returnFalse) - if (opts.allowEmpty === false && v === '') { - return false - } +factory.isPathValid = isPathValid - var regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\/]{3}=)?' - var mimeRegex = '(data:\\w+\\/[a-zA-Z\\+\\-\\.]+;base64,)' +// Fixes typescript +factory.default = factory - if (opts.mimeRequired === true) { - regex = mimeRegex + regex - } else if (opts.allowMime === true) { - regex = mimeRegex + '?' + regex - } +module.exports = factory - if (opts.paddingRequired === false) { - regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' - } +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') - return (new RegExp('^' + regex + '$', 'gi')).test(v) - } + checkPath.convert = makePosix - if (true) { - if ( true && module.exports) { - exports = module.exports = isBase64 - } - exports.isBase64 = isBase64 - } else {} -})(this); + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) +} /***/ }), -/***/ 56873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 98043: +/***/ ((module) => { "use strict"; -var has = __nccwpck_require__(76339); - -function specifierIncluded(current, specifier) { - var nodeParts = current.split('.'); - var parts = specifier.split(' '); - var op = parts.length > 1 ? parts[0] : '='; - var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); - - for (var i = 0; i < 3; ++i) { - var cur = parseInt(nodeParts[i] || 0, 10); - var ver = parseInt(versionParts[i] || 0, 10); - if (cur === ver) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } - if (op === '<') { - return cur < ver; - } - if (op === '>=') { - return cur >= ver; - } - return false; - } - return op === '>='; -} +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; -function matchesRange(current, range) { - var specifiers = range.split(/ ?&& ?/); - if (specifiers.length === 0) { - return false; - } - for (var i = 0; i < specifiers.length; ++i) { - if (!specifierIncluded(current, specifiers[i])) { - return false; - } + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); } - return true; -} -function versionIncluded(nodeVersion, specifierValue) { - if (typeof specifierValue === 'boolean') { - return specifierValue; + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); } - var current = typeof nodeVersion === 'undefined' - ? process.versions && process.versions.node && process.versions.node - : nodeVersion; - - if (typeof current !== 'string') { - throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + if (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); } - if (specifierValue && typeof specifierValue === 'object') { - for (var i = 0; i < specifierValue.length; ++i) { - if (matchesRange(current, specifierValue[i])) { - return true; - } - } - return false; + if (count === 0) { + return string; } - return matchesRange(current, specifierValue); -} -var data = __nccwpck_require__(93991); + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; -module.exports = function isCore(x, nodeVersion) { - return has(data, x) && versionIncluded(nodeVersion, data[x]); + return string.replace(regex, options.indent.repeat(count)); }; /***/ }), -/***/ 64882: -/***/ ((module) => { - -"use strict"; -/* eslint-disable yoda */ +/***/ 44124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +try { + var util = __nccwpck_require__(31669); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = __nccwpck_require__(8544); +} -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } +/***/ }), - return false; -}; +/***/ 8544: +/***/ ((module) => { -module.exports = isFullwidthCodePoint; -module.exports.default = isFullwidthCodePoint; +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} /***/ }), -/***/ 87783: -/***/ ((__unused_webpack_module, exports) => { +/***/ 30545: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -(function(exports) { - "use strict"; +"use strict"; - function isArray(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Array]"; - } else { - return false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(90803); +const utils_1 = __nccwpck_require__(94832); +const RedisParser = __nccwpck_require__(53315); +const SubscriptionSet_1 = __nccwpck_require__(73527); +const debug = utils_1.Debug("dataHandler"); +class DataHandler { + constructor(redis, parserOptions) { + this.redis = redis; + const parser = new RedisParser({ + stringNumbers: parserOptions.stringNumbers, + returnBuffers: !parserOptions.dropBufferSupport, + returnError: (err) => { + this.returnError(err); + }, + returnFatalError: (err) => { + this.returnFatalError(err); + }, + returnReply: (reply) => { + this.returnReply(reply); + }, + }); + redis.stream.on("data", (data) => { + parser.execute(data); + }); } - } - - function isObject(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } else { - return false; + returnFatalError(err) { + err.message += ". Please report this."; + this.redis.recoverFromFatalError(err, err, { offlineQueue: false }); } - } - - function strictDeepEqual(first, second) { - // Check the scalar case first. - if (first === second) { - return true; + returnError(err) { + const item = this.shiftCommand(err); + if (!item) { + return; + } + err.command = { + name: item.command.name, + args: item.command.args, + }; + this.redis.handleReconnection(err, item); } - - // Check if they are the same type. - var firstType = Object.prototype.toString.call(first); - if (firstType !== Object.prototype.toString.call(second)) { - return false; + returnReply(reply) { + if (this.handleMonitorReply(reply)) { + return; + } + if (this.handleSubscriberReply(reply)) { + return; + } + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", item.command.name)) { + this.redis.condition.subscriber = new SubscriptionSet_1.default(); + this.redis.condition.subscriber.add(item.command.name, reply[1].toString()); + if (!fillSubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } + } + else if (command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", item.command.name)) { + if (!fillUnsubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } + } + else { + item.command.resolve(reply); + } } - // We know that first and second have the same type so we can just check the - // first type from now on. - if (isArray(first) === true) { - // Short circuit if they're not the same length; - if (first.length !== second.length) { - return false; - } - for (var i = 0; i < first.length; i++) { - if (strictDeepEqual(first[i], second[i]) === false) { - return false; + handleSubscriberReply(reply) { + if (!this.redis.condition.subscriber) { + return false; } - } - return true; + const replyType = Array.isArray(reply) ? reply[0].toString() : null; + debug('receive reply "%s" in subscriber mode', replyType); + switch (replyType) { + case "message": + if (this.redis.listeners("message").length > 0) { + // Check if there're listeners to avoid unnecessary `toString()`. + this.redis.emit("message", reply[1].toString(), reply[2].toString()); + } + this.redis.emit("messageBuffer", reply[1], reply[2]); + break; + case "pmessage": { + const pattern = reply[1].toString(); + if (this.redis.listeners("pmessage").length > 0) { + this.redis.emit("pmessage", pattern, reply[2].toString(), reply[3].toString()); + } + this.redis.emit("pmessageBuffer", pattern, reply[2], reply[3]); + break; + } + case "subscribe": + case "psubscribe": { + const channel = reply[1].toString(); + this.redis.condition.subscriber.add(replyType, channel); + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (!fillSubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } + break; + } + case "unsubscribe": + case "punsubscribe": { + const channel = reply[1] ? reply[1].toString() : null; + if (channel) { + this.redis.condition.subscriber.del(replyType, channel); + } + const count = reply[2]; + if (count === 0) { + this.redis.condition.subscriber = false; + } + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (!fillUnsubCommand(item.command, count)) { + this.redis.commandQueue.unshift(item); + } + break; + } + default: { + const item = this.shiftCommand(reply); + if (!item) { + return; + } + item.command.resolve(reply); + } + } + return true; } - if (isObject(first) === true) { - // An object is equal if it has the same key/value pairs. - var keysSeen = {}; - for (var key in first) { - if (hasOwnProperty.call(first, key)) { - if (strictDeepEqual(first[key], second[key]) === false) { + handleMonitorReply(reply) { + if (this.redis.status !== "monitoring") { return false; - } - keysSeen[key] = true; } - } - // Now check that there aren't any keys in second that weren't - // in first. - for (var key2 in second) { - if (hasOwnProperty.call(second, key2)) { - if (keysSeen[key2] !== true) { + const replyStr = reply.toString(); + if (replyStr === "OK") { + // Valid commands in the monitoring mode are AUTH and MONITOR, + // both of which always reply with 'OK'. + // So if we got an 'OK', we can make certain that + // the reply is made to AUTH & MONITO. return false; - } } - } - return true; - } - return false; - } - - function isFalse(obj) { - // From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value - - // First check the scalar values. - if (obj === "" || obj === false || obj === null) { - return true; - } else if (isArray(obj) && obj.length === 0) { - // Check for an empty array. + // Since commands sent in the monitoring mode will trigger an exception, + // any replies we received in the monitoring mode should consider to be + // realtime monitor data instead of result of commands. + const len = replyStr.indexOf(" "); + const timestamp = replyStr.slice(0, len); + const argindex = replyStr.indexOf('"'); + const args = replyStr + .slice(argindex + 1, -1) + .split('" "') + .map((elem) => elem.replace(/\\"/g, '"')); + const dbAndSource = replyStr.slice(len + 2, argindex - 2).split(" "); + this.redis.emit("monitor", timestamp, args, dbAndSource[1], dbAndSource[0]); return true; - } else if (isObject(obj)) { - // Check for an empty object. - for (var key in obj) { - // If there are any keys, then - // the object is not empty so the object - // is not false. - if (obj.hasOwnProperty(key)) { - return false; - } + } + shiftCommand(reply) { + const item = this.redis.commandQueue.shift(); + if (!item) { + const message = "Command queue state error. If you can reproduce this, please report it."; + const error = new Error(message + + (reply instanceof Error + ? ` Last error: ${reply.message}` + : ` Last reply: ${reply.toString()}`)); + this.redis.emit("error", error); + return null; } + return item; + } +} +exports.default = DataHandler; +function fillSubCommand(command, count) { + // TODO: use WeakMap here + if (typeof command.remainReplies === "undefined") { + command.remainReplies = command.args.length; + } + if (--command.remainReplies === 0) { + command.resolve(count); return true; - } else { + } + return false; +} +function fillUnsubCommand(command, count) { + if (typeof command.remainReplies === "undefined") { + command.remainReplies = command.args.length; + } + if (command.remainReplies === 0) { + if (count === 0) { + command.resolve(count); + return true; + } return false; } - } - - function objValues(obj) { - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); + if (--command.remainReplies === 0) { + command.resolve(count); + return true; } - return values; - } - - function merge(a, b) { - var merged = {}; - for (var key in a) { - merged[key] = a[key]; - } - for (var key2 in b) { - merged[key2] = b[key2]; - } - return merged; - } - - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; - } else { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; - } - - // Type constants used to define functions. - var TYPE_NUMBER = 0; - var TYPE_ANY = 1; - var TYPE_STRING = 2; - var TYPE_ARRAY = 3; - var TYPE_OBJECT = 4; - var TYPE_BOOLEAN = 5; - var TYPE_EXPREF = 6; - var TYPE_NULL = 7; - var TYPE_ARRAY_NUMBER = 8; - var TYPE_ARRAY_STRING = 9; - - var TOK_EOF = "EOF"; - var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; - var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; - var TOK_RBRACKET = "Rbracket"; - var TOK_RPAREN = "Rparen"; - var TOK_COMMA = "Comma"; - var TOK_COLON = "Colon"; - var TOK_RBRACE = "Rbrace"; - var TOK_NUMBER = "Number"; - var TOK_CURRENT = "Current"; - var TOK_EXPREF = "Expref"; - var TOK_PIPE = "Pipe"; - var TOK_OR = "Or"; - var TOK_AND = "And"; - var TOK_EQ = "EQ"; - var TOK_GT = "GT"; - var TOK_LT = "LT"; - var TOK_GTE = "GTE"; - var TOK_LTE = "LTE"; - var TOK_NE = "NE"; - var TOK_FLATTEN = "Flatten"; - var TOK_STAR = "Star"; - var TOK_FILTER = "Filter"; - var TOK_DOT = "Dot"; - var TOK_NOT = "Not"; - var TOK_LBRACE = "Lbrace"; - var TOK_LBRACKET = "Lbracket"; - var TOK_LPAREN= "Lparen"; - var TOK_LITERAL= "Literal"; - - // The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. + return false; +} - var basicTokens = { - ".": TOK_DOT, - "*": TOK_STAR, - ",": TOK_COMMA, - ":": TOK_COLON, - "{": TOK_LBRACE, - "}": TOK_RBRACE, - "]": TOK_RBRACKET, - "(": TOK_LPAREN, - ")": TOK_RPAREN, - "@": TOK_CURRENT - }; - var operatorStartToken = { - "<": true, - ">": true, - "=": true, - "!": true - }; +/***/ }), - var skipChars = { - " ": true, - "\t": true, - "\n": true - }; +/***/ 6134: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; - function isAlpha(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_"; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stream_1 = __nccwpck_require__(92413); +/** + * Convenient class to convert the process of scaning keys to a readable stream. + * + * @export + * @class ScanStream + * @extends {Readable} + */ +class ScanStream extends stream_1.Readable { + constructor(opt) { + super(opt); + this.opt = opt; + this._redisCursor = "0"; + this._redisDrained = false; + } + _read() { + if (this._redisDrained) { + this.push(null); + return; + } + const args = [this._redisCursor]; + if (this.opt.key) { + args.unshift(this.opt.key); + } + if (this.opt.match) { + args.push("MATCH", this.opt.match); + } + if (this.opt.count) { + args.push("COUNT", String(this.opt.count)); + } + this.opt.redis[this.opt.command](args, (err, res) => { + if (err) { + this.emit("error", err); + return; + } + this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0]; + if (this._redisCursor === "0") { + this._redisDrained = true; + } + this.push(res[1]); + }); + } + close() { + this._redisDrained = true; + } +} +exports.default = ScanStream; - function isNum(ch) { - return (ch >= "0" && ch <= "9") || - ch === "-"; - } - function isAlphaNum(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - (ch >= "0" && ch <= "9") || - ch === "_"; - } - function Lexer() { - } - Lexer.prototype = { - tokenize: function(stream) { - var tokens = []; - this._current = 0; - var start; - var identifier; - var token; - while (this._current < stream.length) { - if (isAlpha(stream[this._current])) { - start = this._current; - identifier = this._consumeUnquotedIdentifier(stream); - tokens.push({type: TOK_UNQUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (basicTokens[stream[this._current]] !== undefined) { - tokens.push({type: basicTokens[stream[this._current]], - value: stream[this._current], - start: this._current}); - this._current++; - } else if (isNum(stream[this._current])) { - token = this._consumeNumber(stream); - tokens.push(token); - } else if (stream[this._current] === "[") { - // No need to increment this._current. This happens - // in _consumeLBracket - token = this._consumeLBracket(stream); - tokens.push(token); - } else if (stream[this._current] === "\"") { - start = this._current; - identifier = this._consumeQuotedIdentifier(stream); - tokens.push({type: TOK_QUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (stream[this._current] === "'") { - start = this._current; - identifier = this._consumeRawStringLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: identifier, - start: start}); - } else if (stream[this._current] === "`") { - start = this._current; - var literal = this._consumeLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: literal, - start: start}); - } else if (operatorStartToken[stream[this._current]] !== undefined) { - tokens.push(this._consumeOperator(stream)); - } else if (skipChars[stream[this._current]] !== undefined) { - // Ignore whitespace. - this._current++; - } else if (stream[this._current] === "&") { - start = this._current; - this._current++; - if (stream[this._current] === "&") { - this._current++; - tokens.push({type: TOK_AND, value: "&&", start: start}); - } else { - tokens.push({type: TOK_EXPREF, value: "&", start: start}); - } - } else if (stream[this._current] === "|") { - start = this._current; - this._current++; - if (stream[this._current] === "|") { - this._current++; - tokens.push({type: TOK_OR, value: "||", start: start}); - } else { - tokens.push({type: TOK_PIPE, value: "|", start: start}); - } - } else { - var error = new Error("Unknown character:" + stream[this._current]); - error.name = "LexerError"; - throw error; - } - } - return tokens; - }, +/***/ }), - _consumeUnquotedIdentifier: function(stream) { - var start = this._current; - this._current++; - while (this._current < stream.length && isAlphaNum(stream[this._current])) { - this._current++; - } - return stream.slice(start, this._current); - }, +/***/ 73527: +/***/ ((__unused_webpack_module, exports) => { - _consumeQuotedIdentifier: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "\"" && this._current < maxLength) { - // You can escape a double quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "\"")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - return JSON.parse(stream.slice(start, this._current)); - }, +"use strict"; - _consumeRawStringLiteral: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "'" && this._current < maxLength) { - // You can escape a single quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "'")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - var literal = stream.slice(start + 1, this._current - 1); - return literal.replace("\\'", "'"); - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Tiny class to simplify dealing with subscription set + * + * @export + * @class SubscriptionSet + */ +class SubscriptionSet { + constructor() { + this.set = { + subscribe: {}, + psubscribe: {}, + }; + } + add(set, channel) { + this.set[mapSet(set)][channel] = true; + } + del(set, channel) { + delete this.set[mapSet(set)][channel]; + } + channels(set) { + return Object.keys(this.set[mapSet(set)]); + } + isEmpty() { + return (this.channels("subscribe").length === 0 && + this.channels("psubscribe").length === 0); + } +} +exports.default = SubscriptionSet; +function mapSet(set) { + if (set === "unsubscribe") { + return "subscribe"; + } + if (set === "punsubscribe") { + return "psubscribe"; + } + return set; +} - _consumeNumber: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (isNum(stream[this._current]) && this._current < maxLength) { - this._current++; - } - var value = parseInt(stream.slice(start, this._current)); - return {type: TOK_NUMBER, value: value, start: start}; - }, - _consumeLBracket: function(stream) { - var start = this._current; - this._current++; - if (stream[this._current] === "?") { - this._current++; - return {type: TOK_FILTER, value: "[?", start: start}; - } else if (stream[this._current] === "]") { - this._current++; - return {type: TOK_FLATTEN, value: "[]", start: start}; - } else { - return {type: TOK_LBRACKET, value: "[", start: start}; - } - }, +/***/ }), - _consumeOperator: function(stream) { - var start = this._current; - var startingChar = stream[start]; - this._current++; - if (startingChar === "!") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_NE, value: "!=", start: start}; - } else { - return {type: TOK_NOT, value: "!", start: start}; - } - } else if (startingChar === "<") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_LTE, value: "<=", start: start}; - } else { - return {type: TOK_LT, value: "<", start: start}; - } - } else if (startingChar === ">") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_GTE, value: ">=", start: start}; - } else { - return {type: TOK_GT, value: ">", start: start}; - } - } else if (startingChar === "=") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_EQ, value: "==", start: start}; - } - } - }, +/***/ 97873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _consumeLiteral: function(stream) { - this._current++; - var start = this._current; - var maxLength = stream.length; - var literal; - while(stream[this._current] !== "`" && this._current < maxLength) { - // You can escape a literal char or you can escape the escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "`")) { - current += 2; - } else { - current++; - } - this._current = current; - } - var literalString = trimLeft(stream.slice(start, this._current)); - literalString = literalString.replace("\\`", "`"); - if (this._looksLikeJSON(literalString)) { - literal = JSON.parse(literalString); - } else { - // Try to JSON parse it as "" - literal = JSON.parse("\"" + literalString + "\""); - } - // +1 gets us to the ending "`", +1 to move on to the next char. - this._current++; - return literal; - }, +"use strict"; - _looksLikeJSON: function(literalString) { - var startingChars = "[{\""; - var jsonLiterals = ["true", "false", "null"]; - var numberLooking = "-0123456789"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const PromiseContainer = __nccwpck_require__(71475); +const calculateSlot = __nccwpck_require__(48481); +const standard_as_callback_1 = __nccwpck_require__(91543); +exports.kExec = Symbol("exec"); +exports.kCallbacks = Symbol("callbacks"); +exports.notAllowedAutoPipelineCommands = [ + "auth", + "info", + "script", + "quit", + "cluster", + "pipeline", + "multi", + "subscribe", + "psubscribe", + "unsubscribe", + "unpsubscribe", +]; +function findAutoPipeline(client, _commandName, ...args) { + if (!client.isCluster) { + return "main"; + } + // We have slot information, we can improve routing by grouping slots served by the same subset of nodes + return client.slots[calculateSlot(args[0])].join(","); +} +function executeAutoPipeline(client, slotKey) { + /* + If a pipeline is already executing, keep queueing up commands + since ioredis won't serve two pipelines at the same time + */ + if (client._runningAutoPipelines.has(slotKey)) { + return; + } + client._runningAutoPipelines.add(slotKey); + // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline + const pipeline = client._autoPipelines.get(slotKey); + client._autoPipelines.delete(slotKey); + const callbacks = pipeline[exports.kCallbacks]; + // Perform the call + pipeline.exec(function (err, results) { + client._runningAutoPipelines.delete(slotKey); + /* + Invoke all callback in nextTick so the stack is cleared + and callbacks can throw errors without affecting other callbacks. + */ + if (err) { + for (let i = 0; i < callbacks.length; i++) { + process.nextTick(callbacks[i], err); + } + } + else { + for (let i = 0; i < callbacks.length; i++) { + process.nextTick(callbacks[i], ...results[i]); + } + } + // If there is another pipeline on the same node, immediately execute it without waiting for nextTick + if (client._autoPipelines.has(slotKey)) { + executeAutoPipeline(client, slotKey); + } + }); +} +function shouldUseAutoPipelining(client, commandName) { + return (client.options.enableAutoPipelining && + !client.isPipeline && + !exports.notAllowedAutoPipelineCommands.includes(commandName) && + !client.options.autoPipeliningIgnoredCommands.includes(commandName)); +} +exports.shouldUseAutoPipelining = shouldUseAutoPipelining; +function executeWithAutoPipelining(client, commandName, args, callback) { + const CustomPromise = PromiseContainer.get(); + // On cluster mode let's wait for slots to be available + if (client.isCluster && !client.slots.length) { + return new CustomPromise(function (resolve, reject) { + client.delayUntilReady((err) => { + if (err) { + reject(err); + return; + } + executeWithAutoPipelining(client, commandName, args, callback).then(resolve, reject); + }); + }); + } + const slotKey = findAutoPipeline(client, commandName, ...args); + if (!client._autoPipelines.has(slotKey)) { + const pipeline = client.pipeline(); + pipeline[exports.kExec] = false; + pipeline[exports.kCallbacks] = []; + client._autoPipelines.set(slotKey, pipeline); + } + const pipeline = client._autoPipelines.get(slotKey); + /* + Mark the pipeline as scheduled. + The symbol will make sure that the pipeline is only scheduled once per tick. + New commands are appended to an already scheduled pipeline. + */ + if (!pipeline[exports.kExec]) { + pipeline[exports.kExec] = true; + /* + Deferring with setImmediate so we have a chance to capture multiple + commands that can be scheduled by I/O events already in the event loop queue. + */ + setImmediate(executeAutoPipeline, client, slotKey); + } + // Create the promise which will execute the + const autoPipelinePromise = new CustomPromise(function (resolve, reject) { + pipeline[exports.kCallbacks].push(function (err, value) { + if (err) { + reject(err); + return; + } + resolve(value); + }); + pipeline[commandName](...args); + }); + return standard_as_callback_1.default(autoPipelinePromise, callback); +} +exports.executeWithAutoPipelining = executeWithAutoPipelining; - if (literalString === "") { - return false; - } else if (startingChars.indexOf(literalString[0]) >= 0) { - return true; - } else if (jsonLiterals.indexOf(literalString) >= 0) { - return true; - } else if (numberLooking.indexOf(literalString[0]) >= 0) { - try { - JSON.parse(literalString); - return true; - } catch (ex) { - return false; - } - } else { - return false; - } - } - }; - var bindingPower = {}; - bindingPower[TOK_EOF] = 0; - bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; - bindingPower[TOK_QUOTEDIDENTIFIER] = 0; - bindingPower[TOK_RBRACKET] = 0; - bindingPower[TOK_RPAREN] = 0; - bindingPower[TOK_COMMA] = 0; - bindingPower[TOK_RBRACE] = 0; - bindingPower[TOK_NUMBER] = 0; - bindingPower[TOK_CURRENT] = 0; - bindingPower[TOK_EXPREF] = 0; - bindingPower[TOK_PIPE] = 1; - bindingPower[TOK_OR] = 2; - bindingPower[TOK_AND] = 3; - bindingPower[TOK_EQ] = 5; - bindingPower[TOK_GT] = 5; - bindingPower[TOK_LT] = 5; - bindingPower[TOK_GTE] = 5; - bindingPower[TOK_LTE] = 5; - bindingPower[TOK_NE] = 5; - bindingPower[TOK_FLATTEN] = 9; - bindingPower[TOK_STAR] = 20; - bindingPower[TOK_FILTER] = 21; - bindingPower[TOK_DOT] = 40; - bindingPower[TOK_NOT] = 45; - bindingPower[TOK_LBRACE] = 50; - bindingPower[TOK_LBRACKET] = 55; - bindingPower[TOK_LPAREN] = 60; +/***/ }), - function Parser() { - } +/***/ 35835: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Parser.prototype = { - parse: function(expression) { - this._loadTokens(expression); - this.index = 0; - var ast = this.expression(0); - if (this._lookahead(0) !== TOK_EOF) { - var t = this._lookaheadToken(0); - var error = new Error( - "Unexpected token type: " + t.type + ", value: " + t.value); - error.name = "ParserError"; - throw error; - } - return ast; - }, +"use strict"; - _loadTokens: function(expression) { - var lexer = new Lexer(); - var tokens = lexer.tokenize(expression); - tokens.push({type: TOK_EOF, value: "", start: expression.length}); - this.tokens = tokens; - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +const dns_1 = __nccwpck_require__(40881); +exports.DEFAULT_CLUSTER_OPTIONS = { + clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000), + enableOfflineQueue: true, + enableReadyCheck: true, + scaleReads: "master", + maxRedirections: 16, + retryDelayOnFailover: 100, + retryDelayOnClusterDown: 100, + retryDelayOnTryAgain: 100, + slotsRefreshTimeout: 1000, + slotsRefreshInterval: 5000, + dnsLookup: dns_1.lookup, + enableAutoPipelining: false, + autoPipeliningIgnoredCommands: [], + maxScriptsCachingTime: 60000, +}; - expression: function(rbp) { - var leftToken = this._lookaheadToken(0); - this._advance(); - var left = this.nud(leftToken); - var currentToken = this._lookahead(0); - while (rbp < bindingPower[currentToken]) { - this._advance(); - left = this.led(currentToken, left); - currentToken = this._lookahead(0); - } - return left; - }, - _lookahead: function(number) { - return this.tokens[this.index + number].type; - }, +/***/ }), - _lookaheadToken: function(number) { - return this.tokens[this.index + number]; - }, +/***/ 18394: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _advance: function() { - this.index++; - }, +"use strict"; - nud: function(token) { - var left; - var right; - var expression; - switch (token.type) { - case TOK_LITERAL: - return {type: "Literal", value: token.value}; - case TOK_UNQUOTEDIDENTIFIER: - return {type: "Field", name: token.value}; - case TOK_QUOTEDIDENTIFIER: - var node = {type: "Field", name: token.value}; - if (this._lookahead(0) === TOK_LPAREN) { - throw new Error("Quoted identifier not allowed for function names."); - } else { - return node; - } - break; - case TOK_NOT: - right = this.expression(bindingPower.Not); - return {type: "NotExpression", children: [right]}; - case TOK_STAR: - left = {type: "Identity"}; - right = null; - if (this._lookahead(0) === TOK_RBRACKET) { - // This can happen in a multiselect, - // [a, b, *] - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Star); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const util_1 = __nccwpck_require__(94582); +const utils_1 = __nccwpck_require__(94832); +const redis_1 = __nccwpck_require__(83609); +const debug = utils_1.Debug("cluster:subscriber"); +const SUBSCRIBER_CONNECTION_NAME = "ioredisClusterSubscriber"; +class ClusterSubscriber { + constructor(connectionPool, emitter) { + this.connectionPool = connectionPool; + this.emitter = emitter; + this.started = false; + this.subscriber = null; + this.connectionPool.on("-node", (_, key) => { + if (!this.started || !this.subscriber) { + return; } - return {type: "ValueProjection", children: [left, right]}; - case TOK_FILTER: - return this.led(token.type, {type: "Identity"}); - case TOK_LBRACE: - return this._parseMultiselectHash(); - case TOK_FLATTEN: - left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; - right = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [left, right]}; - case TOK_LBRACKET: - if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice({type: "Identity"}, right); - } else if (this._lookahead(0) === TOK_STAR && - this._lookahead(1) === TOK_RBRACKET) { - this._advance(); - this._advance(); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", - children: [{type: "Identity"}, right]}; - } else { - return this._parseMultiselectList(); + if (util_1.getNodeKey(this.subscriber.options) === key) { + debug("subscriber has left, selecting a new one..."); + this.selectSubscriber(); } - break; - case TOK_CURRENT: - return {type: TOK_CURRENT}; - case TOK_EXPREF: - expression = this.expression(bindingPower.Expref); - return {type: "ExpressionReference", children: [expression]}; - case TOK_LPAREN: - var args = []; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - args.push(expression); + }); + this.connectionPool.on("+node", () => { + if (!this.started || this.subscriber) { + return; } - this._match(TOK_RPAREN); - return args[0]; - default: - this._errorToken(token); + debug("a new node is discovered and there is no subscriber, selecting a new one..."); + this.selectSubscriber(); + }); + } + getInstance() { + return this.subscriber; + } + selectSubscriber() { + const lastActiveSubscriber = this.lastActiveSubscriber; + // Disconnect the previous subscriber even if there + // will not be a new one. + if (lastActiveSubscriber) { + lastActiveSubscriber.disconnect(); } - }, - - led: function(tokenName, left) { - var right; - switch(tokenName) { - case TOK_DOT: - var rbp = bindingPower.Dot; - if (this._lookahead(0) !== TOK_STAR) { - right = this._parseDotRHS(rbp); - return {type: "Subexpression", children: [left, right]}; - } else { - // Creating a projection. - this._advance(); - right = this._parseProjectionRHS(rbp); - return {type: "ValueProjection", children: [left, right]}; - } - break; - case TOK_PIPE: - right = this.expression(bindingPower.Pipe); - return {type: TOK_PIPE, children: [left, right]}; - case TOK_OR: - right = this.expression(bindingPower.Or); - return {type: "OrExpression", children: [left, right]}; - case TOK_AND: - right = this.expression(bindingPower.And); - return {type: "AndExpression", children: [left, right]}; - case TOK_LPAREN: - var name = left.name; - var args = []; - var expression, node; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } - args.push(expression); - } - this._match(TOK_RPAREN); - node = {type: "Function", name: name, children: args}; - return node; - case TOK_FILTER: - var condition = this.expression(0); - this._match(TOK_RBRACKET); - if (this._lookahead(0) === TOK_FLATTEN) { - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Filter); + const sampleNode = utils_1.sample(this.connectionPool.getNodes()); + if (!sampleNode) { + debug("selecting subscriber failed since there is no node discovered in the cluster yet"); + this.subscriber = null; + return; + } + const { options } = sampleNode; + debug("selected a subscriber %s:%s", options.host, options.port); + /* + * Create a specialized Redis connection for the subscription. + * Note that auto reconnection is enabled here. + * + * `enableReadyCheck` is also enabled because although subscription is allowed + * while redis is loading data from the disk, we can check if the password + * provided for the subscriber is correct, and if not, the current subscriber + * will be disconnected and a new subscriber will be selected. + */ + this.subscriber = new redis_1.default({ + port: options.port, + host: options.host, + username: options.username, + password: options.password, + enableReadyCheck: true, + connectionName: SUBSCRIBER_CONNECTION_NAME, + lazyConnect: true, + tls: options.tls, + }); + // Ignore the errors since they're handled in the connection pool. + this.subscriber.on("error", utils_1.noop); + // Re-subscribe previous channels + const previousChannels = { subscribe: [], psubscribe: [] }; + if (lastActiveSubscriber) { + const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition; + if (condition && condition.subscriber) { + previousChannels.subscribe = condition.subscriber.channels("subscribe"); + previousChannels.psubscribe = condition.subscriber.channels("psubscribe"); } - return {type: "FilterProjection", children: [left, right, condition]}; - case TOK_FLATTEN: - var leftNode = {type: TOK_FLATTEN, children: [left]}; - var rightNode = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [leftNode, rightNode]}; - case TOK_EQ: - case TOK_NE: - case TOK_GT: - case TOK_GTE: - case TOK_LT: - case TOK_LTE: - return this._parseComparator(left, tokenName); - case TOK_LBRACKET: - var token = this._lookaheadToken(0); - if (token.type === TOK_NUMBER || token.type === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice(left, right); - } else { - this._match(TOK_STAR); - this._match(TOK_RBRACKET); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", children: [left, right]}; + } + if (previousChannels.subscribe.length || + previousChannels.psubscribe.length) { + let pending = 0; + for (const type of ["subscribe", "psubscribe"]) { + const channels = previousChannels[type]; + if (channels.length) { + pending += 1; + debug("%s %d channels", type, channels.length); + this.subscriber[type](channels) + .then(() => { + if (!--pending) { + this.lastActiveSubscriber = this.subscriber; + } + }) + .catch(utils_1.noop); + } } - break; - default: - this._errorToken(this._lookaheadToken(0)); } - }, - - _match: function(tokenType) { - if (this._lookahead(0) === tokenType) { - this._advance(); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Expected " + tokenType + ", got: " + t.type); - error.name = "ParserError"; - throw error; - } - }, - - _errorToken: function(token) { - var error = new Error("Invalid token (" + - token.type + "): \"" + - token.value + "\""); - error.name = "ParserError"; - throw error; - }, - - - _parseIndexExpression: function() { - if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { - return this._parseSliceExpression(); - } else { - var node = { - type: "Index", - value: this._lookaheadToken(0).value}; - this._advance(); - this._match(TOK_RBRACKET); - return node; - } - }, - - _projectIfSlice: function(left, right) { - var indexExpr = {type: "IndexExpression", children: [left, right]}; - if (right.type === "Slice") { - return { - type: "Projection", - children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] - }; - } else { - return indexExpr; - } - }, - - _parseSliceExpression: function() { - // [start:end:step] where each part is optional, as well as the last - // colon. - var parts = [null, null, null]; - var index = 0; - var currentToken = this._lookahead(0); - while (currentToken !== TOK_RBRACKET && index < 3) { - if (currentToken === TOK_COLON) { - index++; - this._advance(); - } else if (currentToken === TOK_NUMBER) { - parts[index] = this._lookaheadToken(0).value; - this._advance(); - } else { - var t = this._lookahead(0); - var error = new Error("Syntax error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "Parsererror"; - throw error; - } - currentToken = this._lookahead(0); - } - this._match(TOK_RBRACKET); - return { - type: "Slice", - children: parts - }; - }, + else { + this.lastActiveSubscriber = this.subscriber; + } + for (const event of ["message", "messageBuffer"]) { + this.subscriber.on(event, (arg1, arg2) => { + this.emitter.emit(event, arg1, arg2); + }); + } + for (const event of ["pmessage", "pmessageBuffer"]) { + this.subscriber.on(event, (arg1, arg2, arg3) => { + this.emitter.emit(event, arg1, arg2, arg3); + }); + } + } + start() { + this.started = true; + this.selectSubscriber(); + debug("started"); + } + stop() { + this.started = false; + if (this.subscriber) { + this.subscriber.disconnect(); + this.subscriber = null; + } + debug("stopped"); + } +} +exports.default = ClusterSubscriber; - _parseComparator: function(left, comparator) { - var right = this.expression(bindingPower[comparator]); - return {type: "Comparator", name: comparator, children: [left, right]}; - }, - _parseDotRHS: function(rbp) { - var lookahead = this._lookahead(0); - var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; - if (exprTokens.indexOf(lookahead) >= 0) { - return this.expression(rbp); - } else if (lookahead === TOK_LBRACKET) { - this._match(TOK_LBRACKET); - return this._parseMultiselectList(); - } else if (lookahead === TOK_LBRACE) { - this._match(TOK_LBRACE); - return this._parseMultiselectHash(); - } - }, +/***/ }), - _parseProjectionRHS: function(rbp) { - var right; - if (bindingPower[this._lookahead(0)] < 10) { - right = {type: "Identity"}; - } else if (this._lookahead(0) === TOK_LBRACKET) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_FILTER) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_DOT) { - this._match(TOK_DOT); - right = this._parseDotRHS(rbp); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Sytanx error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "ParserError"; - throw error; - } - return right; - }, +/***/ 34589: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _parseMultiselectList: function() { - var expressions = []; - while (this._lookahead(0) !== TOK_RBRACKET) { - var expression = this.expression(0); - expressions.push(expression); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - if (this._lookahead(0) === TOK_RBRACKET) { - throw new Error("Unexpected token Rbracket"); - } - } - } - this._match(TOK_RBRACKET); - return {type: "MultiSelectList", children: expressions}; - }, +"use strict"; - _parseMultiselectHash: function() { - var pairs = []; - var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; - var keyToken, keyName, value, node; - for (;;) { - keyToken = this._lookaheadToken(0); - if (identifierTypes.indexOf(keyToken.type) < 0) { - throw new Error("Expecting an identifier token, got: " + - keyToken.type); - } - keyName = keyToken.value; - this._advance(); - this._match(TOK_COLON); - value = this.expression(0); - node = {type: "KeyValuePair", name: keyName, value: value}; - pairs.push(node); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } else if (this._lookahead(0) === TOK_RBRACE) { - this._match(TOK_RBRACE); - break; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(28614); +const utils_1 = __nccwpck_require__(94832); +const util_1 = __nccwpck_require__(94582); +const redis_1 = __nccwpck_require__(83609); +const debug = utils_1.Debug("cluster:connectionPool"); +class ConnectionPool extends events_1.EventEmitter { + constructor(redisOptions) { + super(); + this.redisOptions = redisOptions; + // master + slave = all + this.nodes = { + all: {}, + master: {}, + slave: {}, + }; + this.specifiedOptions = {}; + } + getNodes(role = "all") { + const nodes = this.nodes[role]; + return Object.keys(nodes).map((key) => nodes[key]); + } + getInstanceByKey(key) { + return this.nodes.all[key]; + } + getSampleInstance(role) { + const keys = Object.keys(this.nodes[role]); + const sampleKey = utils_1.sample(keys); + return this.nodes[role][sampleKey]; + } + /** + * Find or create a connection to the node + * + * @param {IRedisOptions} node + * @param {boolean} [readOnly=false] + * @returns {*} + * @memberof ConnectionPool + */ + findOrCreate(node, readOnly = false) { + const key = util_1.getNodeKey(node); + readOnly = Boolean(readOnly); + if (this.specifiedOptions[key]) { + Object.assign(node, this.specifiedOptions[key]); } - return {type: "MultiSelectHash", children: pairs}; - } - }; - - - function TreeInterpreter(runtime) { - this.runtime = runtime; - } - - TreeInterpreter.prototype = { - search: function(node, value) { - return this.visit(node, value); - }, - - visit: function(node, value) { - var matched, current, result, first, second, field, left, right, collected, i; - switch (node.type) { - case "Field": - if (value === null ) { - return null; - } else if (isObject(value)) { - field = value[node.name]; - if (field === undefined) { - return null; - } else { - return field; - } - } else { - return null; - } - break; - case "Subexpression": - result = this.visit(node.children[0], value); - for (i = 1; i < node.children.length; i++) { - result = this.visit(node.children[1], result); - if (result === null) { - return null; - } - } - return result; - case "IndexExpression": - left = this.visit(node.children[0], value); - right = this.visit(node.children[1], left); - return right; - case "Index": - if (!isArray(value)) { - return null; - } - var index = node.value; - if (index < 0) { - index = value.length + index; - } - result = value[index]; - if (result === undefined) { - result = null; - } - return result; - case "Slice": - if (!isArray(value)) { - return null; - } - var sliceParams = node.children.slice(0); - var computed = this.computeSliceParams(value.length, sliceParams); - var start = computed[0]; - var stop = computed[1]; - var step = computed[2]; - result = []; - if (step > 0) { - for (i = start; i < stop; i += step) { - result.push(value[i]); - } - } else { - for (i = start; i > stop; i += step) { - result.push(value[i]); - } - } - return result; - case "Projection": - // Evaluate left child. - var base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - collected = []; - for (i = 0; i < base.length; i++) { - current = this.visit(node.children[1], base[i]); - if (current !== null) { - collected.push(current); - } - } - return collected; - case "ValueProjection": - // Evaluate left child. - base = this.visit(node.children[0], value); - if (!isObject(base)) { - return null; - } - collected = []; - var values = objValues(base); - for (i = 0; i < values.length; i++) { - current = this.visit(node.children[1], values[i]); - if (current !== null) { - collected.push(current); - } - } - return collected; - case "FilterProjection": - base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - var filtered = []; - var finalResults = []; - for (i = 0; i < base.length; i++) { - matched = this.visit(node.children[2], base[i]); - if (!isFalse(matched)) { - filtered.push(base[i]); + else { + this.specifiedOptions[key] = node; + } + let redis; + if (this.nodes.all[key]) { + redis = this.nodes.all[key]; + if (redis.options.readOnly !== readOnly) { + redis.options.readOnly = readOnly; + debug("Change role of %s to %s", key, readOnly ? "slave" : "master"); + redis[readOnly ? "readonly" : "readwrite"]().catch(utils_1.noop); + if (readOnly) { + delete this.nodes.master[key]; + this.nodes.slave[key] = redis; } - } - for (var j = 0; j < filtered.length; j++) { - current = this.visit(node.children[1], filtered[j]); - if (current !== null) { - finalResults.push(current); + else { + delete this.nodes.slave[key]; + this.nodes.master[key] = redis; } - } - return finalResults; - case "Comparator": - first = this.visit(node.children[0], value); - second = this.visit(node.children[1], value); - switch(node.name) { - case TOK_EQ: - result = strictDeepEqual(first, second); - break; - case TOK_NE: - result = !strictDeepEqual(first, second); - break; - case TOK_GT: - result = first > second; - break; - case TOK_GTE: - result = first >= second; - break; - case TOK_LT: - result = first < second; - break; - case TOK_LTE: - result = first <= second; - break; - default: - throw new Error("Unknown comparator: " + node.name); - } - return result; - case TOK_FLATTEN: - var original = this.visit(node.children[0], value); - if (!isArray(original)) { - return null; - } - var merged = []; - for (i = 0; i < original.length; i++) { - current = original[i]; - if (isArray(current)) { - merged.push.apply(merged, current); - } else { - merged.push(current); + } + } + else { + debug("Connecting to %s as %s", key, readOnly ? "slave" : "master"); + redis = new redis_1.default(utils_1.defaults({ + // Never try to reconnect when a node is lose, + // instead, waiting for a `MOVED` error and + // fetch the slots again. + retryStrategy: null, + // Offline queue should be enabled so that + // we don't need to wait for the `ready` event + // before sending commands to the node. + enableOfflineQueue: true, + readOnly: readOnly, + }, node, this.redisOptions, { lazyConnect: true })); + this.nodes.all[key] = redis; + this.nodes[readOnly ? "slave" : "master"][key] = redis; + redis.once("end", () => { + this.removeNode(key); + this.emit("-node", redis, key); + if (!Object.keys(this.nodes.all).length) { + this.emit("drain"); } - } - return merged; - case "Identity": - return value; - case "MultiSelectList": - if (value === null) { - return null; - } - collected = []; - for (i = 0; i < node.children.length; i++) { - collected.push(this.visit(node.children[i], value)); - } - return collected; - case "MultiSelectHash": - if (value === null) { - return null; - } - collected = {}; - var child; - for (i = 0; i < node.children.length; i++) { - child = node.children[i]; - collected[child.name] = this.visit(child.value, value); - } - return collected; - case "OrExpression": - matched = this.visit(node.children[0], value); - if (isFalse(matched)) { - matched = this.visit(node.children[1], value); - } - return matched; - case "AndExpression": - first = this.visit(node.children[0], value); + }); + this.emit("+node", redis, key); + redis.on("error", function (error) { + this.emit("nodeError", error, key); + }); + } + return redis; + } + /** + * Remove a node from the pool. + */ + removeNode(key) { + const { nodes } = this; + if (nodes.all[key]) { + debug("Remove %s from the pool", key); + delete nodes.all[key]; + } + delete nodes.master[key]; + delete nodes.slave[key]; + } + /** + * Reset the pool with a set of nodes. + * The old node will be removed. + * + * @param {(Array)} nodes + * @memberof ConnectionPool + */ + reset(nodes) { + debug("Reset with %O", nodes); + const newNodes = {}; + nodes.forEach((node) => { + const key = util_1.getNodeKey(node); + // Don't override the existing (master) node + // when the current one is slave. + if (!(node.readOnly && newNodes[key])) { + newNodes[key] = node; + } + }); + Object.keys(this.nodes.all).forEach((key) => { + if (!newNodes[key]) { + debug("Disconnect %s because the node does not hold any slot", key); + this.nodes.all[key].disconnect(); + this.removeNode(key); + } + }); + Object.keys(newNodes).forEach((key) => { + const node = newNodes[key]; + this.findOrCreate(node, node.readOnly); + }); + } +} +exports.default = ConnectionPool; - if (isFalse(first) === true) { - return first; - } - return this.visit(node.children[1], value); - case "NotExpression": - first = this.visit(node.children[0], value); - return isFalse(first); - case "Literal": - return node.value; - case TOK_PIPE: - left = this.visit(node.children[0], value); - return this.visit(node.children[1], left); - case TOK_CURRENT: - return value; - case "Function": - var resolvedArgs = []; - for (i = 0; i < node.children.length; i++) { - resolvedArgs.push(this.visit(node.children[i], value)); - } - return this.runtime.callFunction(node.name, resolvedArgs); - case "ExpressionReference": - var refNode = node.children[0]; - // Tag the node with a specific attribute so the type - // checker verify the type. - refNode.jmespathType = TOK_EXPREF; - return refNode; - default: - throw new Error("Unknown node type: " + node.type); - } - }, - computeSliceParams: function(arrayLength, sliceParams) { - var start = sliceParams[0]; - var stop = sliceParams[1]; - var step = sliceParams[2]; - var computed = [null, null, null]; - if (step === null) { - step = 1; - } else if (step === 0) { - var error = new Error("Invalid slice, step cannot be 0"); - error.name = "RuntimeError"; - throw error; - } - var stepValueNegative = step < 0 ? true : false; +/***/ }), - if (start === null) { - start = stepValueNegative ? arrayLength - 1 : 0; - } else { - start = this.capSliceRange(arrayLength, start, step); +/***/ 12770: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const Deque = __nccwpck_require__(42342); +const debug = utils_1.Debug("delayqueue"); +/** + * Queue that runs items after specified duration + * + * @export + * @class DelayQueue + */ +class DelayQueue { + constructor() { + this.queues = {}; + this.timeouts = {}; + } + /** + * Add a new item to the queue + * + * @param {string} bucket bucket name + * @param {Function} item function that will run later + * @param {IDelayQueueOptions} options + * @memberof DelayQueue + */ + push(bucket, item, options) { + const callback = options.callback || process.nextTick; + if (!this.queues[bucket]) { + this.queues[bucket] = new Deque(); + } + const queue = this.queues[bucket]; + queue.push(item); + if (!this.timeouts[bucket]) { + this.timeouts[bucket] = setTimeout(() => { + callback(() => { + this.timeouts[bucket] = null; + this.execute(bucket); + }); + }, options.timeout); + } + } + execute(bucket) { + const queue = this.queues[bucket]; + if (!queue) { + return; } - - if (stop === null) { - stop = stepValueNegative ? -1 : arrayLength; - } else { - stop = this.capSliceRange(arrayLength, stop, step); + const { length } = queue; + if (!length) { + return; } - computed[0] = start; - computed[1] = stop; - computed[2] = step; - return computed; - }, + debug("send %d commands in %s queue", length, bucket); + this.queues[bucket] = null; + while (queue.length > 0) { + queue.shift()(); + } + } +} +exports.default = DelayQueue; - capSliceRange: function(arrayLength, actualValue, step) { - if (actualValue < 0) { - actualValue += arrayLength; - if (actualValue < 0) { - actualValue = step < 0 ? -1 : 0; - } - } else if (actualValue >= arrayLength) { - actualValue = step < 0 ? arrayLength - 1 : arrayLength; - } - return actualValue; - } - }; +/***/ }), - function Runtime(interpreter) { - this._interpreter = interpreter; - this.functionTable = { - // name: [function, ] - // The can be: - // - // { - // args: [[type1, type2], [type1, type2]], - // variadic: true|false - // } - // - // Each arg in the arg list is a list of valid types - // (if the function is overloaded and supports multiple - // types. If the type is "any" then no type checking - // occurs on the argument. Variadic is optional - // and if not provided is assumed to be false. - abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, - avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, - contains: { - _func: this._functionContains, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, - {types: [TYPE_ANY]}]}, - "ends_with": { - _func: this._functionEndsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, - length: { - _func: this._functionLength, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, - map: { - _func: this._functionMap, - _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, - max: { - _func: this._functionMax, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "merge": { - _func: this._functionMerge, - _signature: [{types: [TYPE_OBJECT], variadic: true}] - }, - "max_by": { - _func: this._functionMaxBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - "starts_with": { - _func: this._functionStartsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - min: { - _func: this._functionMin, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "min_by": { - _func: this._functionMinBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, - keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, - values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, - sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, - "sort_by": { - _func: this._functionSortBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - join: { - _func: this._functionJoin, - _signature: [ - {types: [TYPE_STRING]}, - {types: [TYPE_ARRAY_STRING]} - ] - }, - reverse: { - _func: this._functionReverse, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, - "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, - "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, - "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, - "not_null": { - _func: this._functionNotNull, - _signature: [{types: [TYPE_ANY], variadic: true}] - } - }; - } +/***/ 17208: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Runtime.prototype = { - callFunction: function(name, resolvedArgs) { - var functionEntry = this.functionTable[name]; - if (functionEntry === undefined) { - throw new Error("Unknown function: " + name + "()"); - } - this._validateArgs(name, resolvedArgs, functionEntry._signature); - return functionEntry._func.call(this, resolvedArgs); - }, +"use strict"; - _validateArgs: function(name, args, signature) { - // Validating the args requires validating - // the correct arity and the correct type of each arg. - // If the last argument is declared as variadic, then we need - // a minimum number of args to be required. Otherwise it has to - // be an exact amount. - var pluralized; - if (signature[signature.length - 1].variadic) { - if (args.length < signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes at least" + signature.length + pluralized + - " but received " + args.length); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(28614); +const ClusterAllFailedError_1 = __nccwpck_require__(97282); +const utils_1 = __nccwpck_require__(94832); +const ConnectionPool_1 = __nccwpck_require__(34589); +const util_1 = __nccwpck_require__(94582); +const ClusterSubscriber_1 = __nccwpck_require__(18394); +const DelayQueue_1 = __nccwpck_require__(12770); +const ScanStream_1 = __nccwpck_require__(6134); +const redis_errors_1 = __nccwpck_require__(81879); +const standard_as_callback_1 = __nccwpck_require__(91543); +const PromiseContainer = __nccwpck_require__(71475); +const ClusterOptions_1 = __nccwpck_require__(35835); +const utils_2 = __nccwpck_require__(94832); +const commands = __nccwpck_require__(98020); +const command_1 = __nccwpck_require__(90803); +const redis_1 = __nccwpck_require__(83609); +const commander_1 = __nccwpck_require__(33642); +const Deque = __nccwpck_require__(42342); +const debug = utils_1.Debug("cluster"); +/** + * Client for the official Redis Cluster + * + * @class Cluster + * @extends {EventEmitter} + */ +class Cluster extends events_1.EventEmitter { + /** + * Creates an instance of Cluster. + * + * @param {((string | number | object)[])} startupNodes + * @param {IClusterOptions} [options={}] + * @memberof Cluster + */ + constructor(startupNodes, options = {}) { + super(); + this.slots = []; + this.retryAttempts = 0; + this.delayQueue = new DelayQueue_1.default(); + this.offlineQueue = new Deque(); + this.isRefreshing = false; + this.isCluster = true; + this._autoPipelines = new Map(); + this._runningAutoPipelines = new Set(); + this._readyDelayedCallbacks = []; + this._addedScriptHashes = {}; + /** + * Every time Cluster#connect() is called, this value will be + * auto-incrementing. The purpose of this value is used for + * discarding previous connect attampts when creating a new + * connection. + * + * @private + * @type {number} + * @memberof Cluster + */ + this.connectionEpoch = 0; + commander_1.default.call(this); + this.startupNodes = startupNodes; + this.options = utils_1.defaults({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options); + // validate options + if (typeof this.options.scaleReads !== "function" && + ["all", "master", "slave"].indexOf(this.options.scaleReads) === -1) { + throw new Error('Invalid option scaleReads "' + + this.options.scaleReads + + '". Expected "all", "master", "slave" or a custom function'); + } + this.connectionPool = new ConnectionPool_1.default(this.options.redisOptions); + this.connectionPool.on("-node", (redis, key) => { + this.emit("-node", redis); + }); + this.connectionPool.on("+node", (redis) => { + this.emit("+node", redis); + }); + this.connectionPool.on("drain", () => { + this.setStatus("close"); + }); + this.connectionPool.on("nodeError", (error, key) => { + this.emit("node error", error, key); + }); + this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this); + if (this.options.lazyConnect) { + this.setStatus("wait"); + } + else { + this.connect().catch((err) => { + debug("connecting failed: %s", err); + }); + } + } + resetOfflineQueue() { + this.offlineQueue = new Deque(); + } + clearNodesRefreshInterval() { + if (this.slotsTimer) { + clearTimeout(this.slotsTimer); + this.slotsTimer = null; + } + } + resetNodesRefreshInterval() { + if (this.slotsTimer) { + return; + } + const nextRound = () => { + this.slotsTimer = setTimeout(() => { + debug('refreshing slot caches... (triggered by "slotsRefreshInterval" option)'); + this.refreshSlotsCache(() => { + nextRound(); + }); + }, this.options.slotsRefreshInterval); + }; + nextRound(); + } + /** + * Connect to a cluster + * + * @returns {Promise} + * @memberof Cluster + */ + connect() { + const Promise = PromiseContainer.get(); + return new Promise((resolve, reject) => { + if (this.status === "connecting" || + this.status === "connect" || + this.status === "ready") { + reject(new Error("Redis is already connecting/connected")); + return; + } + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = setInterval(() => { + this._addedScriptHashes = {}; + }, this.options.maxScriptsCachingTime); + const epoch = ++this.connectionEpoch; + this.setStatus("connecting"); + this.resolveStartupNodeHostnames() + .then((nodes) => { + if (this.connectionEpoch !== epoch) { + debug("discard connecting after resolving startup nodes because epoch not match: %d != %d", epoch, this.connectionEpoch); + reject(new redis_errors_1.RedisError("Connection is discarded because a new connection is made")); + return; + } + if (this.status !== "connecting") { + debug("discard connecting after resolving startup nodes because the status changed to %s", this.status); + reject(new redis_errors_1.RedisError("Connection is aborted")); + return; + } + this.connectionPool.reset(nodes); + function readyHandler() { + this.setStatus("ready"); + this.retryAttempts = 0; + this.executeOfflineCommands(); + this.resetNodesRefreshInterval(); + resolve(); + } + let closeListener = undefined; + const refreshListener = () => { + this.invokeReadyDelayedCallbacks(undefined); + this.removeListener("close", closeListener); + this.manuallyClosing = false; + this.setStatus("connect"); + if (this.options.enableReadyCheck) { + this.readyCheck((err, fail) => { + if (err || fail) { + debug("Ready check failed (%s). Reconnecting...", err || fail); + if (this.status === "connect") { + this.disconnect(true); + } + } + else { + readyHandler.call(this); + } + }); + } + else { + readyHandler.call(this); + } + }; + closeListener = function () { + const error = new Error("None of startup nodes is available"); + this.removeListener("refresh", refreshListener); + this.invokeReadyDelayedCallbacks(error); + reject(error); + }; + this.once("refresh", refreshListener); + this.once("close", closeListener); + this.once("close", this.handleCloseEvent.bind(this)); + this.refreshSlotsCache(function (err) { + if (err && err.message === "Failed to refresh slots cache.") { + redis_1.default.prototype.silentEmit.call(this, "error", err); + this.connectionPool.reset([]); + } + }.bind(this)); + this.subscriber.start(); + }) + .catch((err) => { + this.setStatus("close"); + this.handleCloseEvent(err); + this.invokeReadyDelayedCallbacks(err); + reject(err); + }); + }); + } + /** + * Called when closed to check whether a reconnection should be made + * + * @private + * @memberof Cluster + */ + handleCloseEvent(reason) { + if (reason) { + debug("closed because %s", reason); + } + let retryDelay; + if (!this.manuallyClosing && + typeof this.options.clusterRetryStrategy === "function") { + retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason); + } + if (typeof retryDelay === "number") { + this.setStatus("reconnecting"); + this.reconnectTimeout = setTimeout(function () { + this.reconnectTimeout = null; + debug("Cluster is disconnected. Retrying after %dms", retryDelay); + this.connect().catch(function (err) { + debug("Got error %s when reconnecting. Ignoring...", err); + }); + }.bind(this), retryDelay); + } + else { + this.setStatus("end"); + this.flushQueue(new Error("None of startup nodes is available")); + } + } + /** + * Disconnect from every node in the cluster. + * + * @param {boolean} [reconnect=false] + * @memberof Cluster + */ + disconnect(reconnect = false) { + const status = this.status; + this.setStatus("disconnecting"); + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + if (!reconnect) { + this.manuallyClosing = true; + } + if (this.reconnectTimeout && !reconnect) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; + debug("Canceled reconnecting attempts"); + } + this.clearNodesRefreshInterval(); + this.subscriber.stop(); + if (status === "wait") { + this.setStatus("close"); + this.handleCloseEvent(); + } + else { + this.connectionPool.reset([]); + } + } + /** + * Quit the cluster gracefully. + * + * @param {CallbackFunction<'OK'>} [callback] + * @returns {Promise<'OK'>} + * @memberof Cluster + */ + quit(callback) { + const status = this.status; + this.setStatus("disconnecting"); + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + this.manuallyClosing = true; + if (this.reconnectTimeout) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; + } + this.clearNodesRefreshInterval(); + this.subscriber.stop(); + const Promise = PromiseContainer.get(); + if (status === "wait") { + const ret = standard_as_callback_1.default(Promise.resolve("OK"), callback); + // use setImmediate to make sure "close" event + // being emitted after quit() is returned + setImmediate(function () { + this.setStatus("close"); + this.handleCloseEvent(); + }.bind(this)); + return ret; + } + return standard_as_callback_1.default(Promise.all(this.nodes().map((node) => node.quit().catch((err) => { + // Ignore the error caused by disconnecting since + // we're disconnecting... + if (err.message === utils_2.CONNECTION_CLOSED_ERROR_MSG) { + return "OK"; + } + throw err; + }))).then(() => "OK"), callback); + } + /** + * Create a new instance with the same startup nodes and options as the current one. + * + * @example + * ```js + * var cluster = new Redis.Cluster([{ host: "127.0.0.1", port: "30001" }]); + * var anotherCluster = cluster.duplicate(); + * ``` + * + * @public + * @param {((string | number | object)[])} [overrideStartupNodes=[]] + * @param {IClusterOptions} [overrideOptions={}] + * @memberof Cluster + */ + duplicate(overrideStartupNodes = [], overrideOptions = {}) { + const startupNodes = overrideStartupNodes.length > 0 + ? overrideStartupNodes + : this.startupNodes.slice(0); + const options = Object.assign({}, this.options, overrideOptions); + return new Cluster(startupNodes, options); + } + /** + * Get nodes with the specified role + * + * @param {NodeRole} [role='all'] + * @returns {any[]} + * @memberof Cluster + */ + nodes(role = "all") { + if (role !== "all" && role !== "master" && role !== "slave") { + throw new Error('Invalid role "' + role + '". Expected "all", "master" or "slave"'); + } + return this.connectionPool.getNodes(role); + } + // This is needed in order not to install a listener for each auto pipeline + delayUntilReady(callback) { + this._readyDelayedCallbacks.push(callback); + } + /** + * Get the number of commands queued in automatic pipelines. + * + * This is not available (and returns 0) until the cluster is connected and slots information have been received. + */ + get autoPipelineQueueSize() { + let queued = 0; + for (const pipeline of this._autoPipelines.values()) { + queued += pipeline.length; + } + return queued; + } + /** + * Change cluster instance's status + * + * @private + * @param {ClusterStatus} status + * @memberof Cluster + */ + setStatus(status) { + debug("status: %s -> %s", this.status || "[empty]", status); + this.status = status; + process.nextTick(() => { + this.emit(status); + }); + } + /** + * Refresh the slot cache + * + * @private + * @param {CallbackFunction} [callback] + * @memberof Cluster + */ + refreshSlotsCache(callback) { + if (this.isRefreshing) { + if (typeof callback === "function") { + process.nextTick(callback); } - } else if (args.length !== signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes " + signature.length + pluralized + - " but received " + args.length); + return; } - var currentSpec; - var actualType; - var typeMatched; - for (var i = 0; i < signature.length; i++) { - typeMatched = false; - currentSpec = signature[i].types; - actualType = this._getTypeName(args[i]); - for (var j = 0; j < currentSpec.length; j++) { - if (this._typeMatches(actualType, currentSpec[j], args[i])) { - typeMatched = true; - break; - } + this.isRefreshing = true; + const _this = this; + const wrapper = function (error) { + _this.isRefreshing = false; + if (typeof callback === "function") { + callback(error); } - if (!typeMatched) { - throw new Error("TypeError: " + name + "() " + - "expected argument " + (i + 1) + - " to be type " + currentSpec + - " but received type " + actualType + - " instead."); + }; + const nodes = utils_2.shuffle(this.connectionPool.getNodes()); + let lastNodeError = null; + function tryNode(index) { + if (index === nodes.length) { + const error = new ClusterAllFailedError_1.default("Failed to refresh slots cache.", lastNodeError); + return wrapper(error); } - } - }, - - _typeMatches: function(actual, expected, argValue) { - if (expected === TYPE_ANY) { - return true; - } - if (expected === TYPE_ARRAY_STRING || - expected === TYPE_ARRAY_NUMBER || - expected === TYPE_ARRAY) { - // The expected type can either just be array, - // or it can require a specific subtype (array of numbers). - // - // The simplest case is if "array" with no subtype is specified. - if (expected === TYPE_ARRAY) { - return actual === TYPE_ARRAY; - } else if (actual === TYPE_ARRAY) { - // Otherwise we need to check subtypes. - // I think this has potential to be improved. - var subtype; - if (expected === TYPE_ARRAY_NUMBER) { - subtype = TYPE_NUMBER; - } else if (expected === TYPE_ARRAY_STRING) { - subtype = TYPE_STRING; + const node = nodes[index]; + const key = `${node.options.host}:${node.options.port}`; + debug("getting slot cache from %s", key); + _this.getInfoFromNode(node, function (err) { + switch (_this.status) { + case "close": + case "end": + return wrapper(new Error("Cluster is disconnected.")); + case "disconnecting": + return wrapper(new Error("Cluster is disconnecting.")); } - for (var i = 0; i < argValue.length; i++) { - if (!this._typeMatches( - this._getTypeName(argValue[i]), subtype, - argValue[i])) { - return false; - } + if (err) { + _this.emit("node error", err, key); + lastNodeError = err; + tryNode(index + 1); } - return true; - } - } else { - return actual === expected; - } - }, - _getTypeName: function(obj) { - switch (Object.prototype.toString.call(obj)) { - case "[object String]": - return TYPE_STRING; - case "[object Number]": - return TYPE_NUMBER; - case "[object Array]": - return TYPE_ARRAY; - case "[object Boolean]": - return TYPE_BOOLEAN; - case "[object Null]": - return TYPE_NULL; - case "[object Object]": - // Check if it's an expref. If it has, it's been - // tagged with a jmespathType attr of 'Expref'; - if (obj.jmespathType === TOK_EXPREF) { - return TYPE_EXPREF; - } else { - return TYPE_OBJECT; - } - } - }, - - _functionStartsWith: function(resolvedArgs) { - return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; - }, - - _functionEndsWith: function(resolvedArgs) { - var searchStr = resolvedArgs[0]; - var suffix = resolvedArgs[1]; - return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; - }, - - _functionReverse: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - if (typeName === TYPE_STRING) { - var originalStr = resolvedArgs[0]; - var reversedStr = ""; - for (var i = originalStr.length - 1; i >= 0; i--) { - reversedStr += originalStr[i]; - } - return reversedStr; - } else { - var reversedArray = resolvedArgs[0].slice(0); - reversedArray.reverse(); - return reversedArray; - } - }, - - _functionAbs: function(resolvedArgs) { - return Math.abs(resolvedArgs[0]); - }, - - _functionCeil: function(resolvedArgs) { - return Math.ceil(resolvedArgs[0]); - }, - - _functionAvg: function(resolvedArgs) { - var sum = 0; - var inputArray = resolvedArgs[0]; - for (var i = 0; i < inputArray.length; i++) { - sum += inputArray[i]; + else { + _this.emit("refresh"); + wrapper(); + } + }); } - return sum / inputArray.length; - }, - - _functionContains: function(resolvedArgs) { - return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; - }, - - _functionFloor: function(resolvedArgs) { - return Math.floor(resolvedArgs[0]); - }, - - _functionLength: function(resolvedArgs) { - if (!isObject(resolvedArgs[0])) { - return resolvedArgs[0].length; - } else { - // As far as I can tell, there's no way to get the length - // of an object without O(n) iteration through the object. - return Object.keys(resolvedArgs[0]).length; - } - }, - - _functionMap: function(resolvedArgs) { - var mapped = []; - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[0]; - var elements = resolvedArgs[1]; - for (var i = 0; i < elements.length; i++) { - mapped.push(interpreter.visit(exprefNode, elements[i])); - } - return mapped; - }, - - _functionMerge: function(resolvedArgs) { - var merged = {}; - for (var i = 0; i < resolvedArgs.length; i++) { - var current = resolvedArgs[i]; - for (var key in current) { - merged[key] = current[key]; + tryNode(0); + } + /** + * Flush offline queue with error. + * + * @param {Error} error + * @memberof Cluster + */ + flushQueue(error) { + let item; + while (this.offlineQueue.length > 0) { + item = this.offlineQueue.shift(); + item.command.reject(error); } - } - return merged; - }, - - _functionMax: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.max.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var maxElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (maxElement.localeCompare(elements[i]) < 0) { - maxElement = elements[i]; - } - } - return maxElement; + } + executeOfflineCommands() { + if (this.offlineQueue.length) { + debug("send %d commands in offline queue", this.offlineQueue.length); + const offlineQueue = this.offlineQueue; + this.resetOfflineQueue(); + while (offlineQueue.length > 0) { + const item = offlineQueue.shift(); + this.sendCommand(item.command, item.stream, item.node); + } } - } else { - return null; - } - }, - - _functionMin: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.min.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var minElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (elements[i].localeCompare(minElement) < 0) { - minElement = elements[i]; - } - } - return minElement; + } + natMapper(nodeKey) { + if (this.options.natMap && typeof this.options.natMap === "object") { + const key = typeof nodeKey === "string" + ? nodeKey + : `${nodeKey.host}:${nodeKey.port}`; + const mapped = this.options.natMap[key]; + if (mapped) { + debug("NAT mapping %s -> %O", key, mapped); + return Object.assign({}, mapped); + } } - } else { - return null; - } - }, - - _functionSum: function(resolvedArgs) { - var sum = 0; - var listToSum = resolvedArgs[0]; - for (var i = 0; i < listToSum.length; i++) { - sum += listToSum[i]; - } - return sum; - }, - - _functionType: function(resolvedArgs) { - switch (this._getTypeName(resolvedArgs[0])) { - case TYPE_NUMBER: - return "number"; - case TYPE_STRING: - return "string"; - case TYPE_ARRAY: - return "array"; - case TYPE_OBJECT: - return "object"; - case TYPE_BOOLEAN: - return "boolean"; - case TYPE_EXPREF: - return "expref"; - case TYPE_NULL: - return "null"; + return typeof nodeKey === "string" + ? util_1.nodeKeyToRedisOptions(nodeKey) + : nodeKey; + } + sendCommand(command, stream, node) { + if (this.status === "wait") { + this.connect().catch(utils_1.noop); } - }, - - _functionKeys: function(resolvedArgs) { - return Object.keys(resolvedArgs[0]); - }, - - _functionValues: function(resolvedArgs) { - var obj = resolvedArgs[0]; - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); + if (this.status === "end") { + command.reject(new Error(utils_2.CONNECTION_CLOSED_ERROR_MSG)); + return command.promise; } - return values; - }, - - _functionJoin: function(resolvedArgs) { - var joinChar = resolvedArgs[0]; - var listJoin = resolvedArgs[1]; - return listJoin.join(joinChar); - }, - - _functionToArray: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { - return resolvedArgs[0]; - } else { - return [resolvedArgs[0]]; + let to = this.options.scaleReads; + if (to !== "master") { + const isCommandReadOnly = command.isReadOnly || + (commands.exists(command.name) && + commands.hasFlag(command.name, "readonly")); + if (!isCommandReadOnly) { + to = "master"; + } } - }, - - _functionToString: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { - return resolvedArgs[0]; - } else { - return JSON.stringify(resolvedArgs[0]); + let targetSlot = node ? node.slot : command.getSlot(); + const ttl = {}; + const _this = this; + if (!node && !command.__is_reject_overwritten) { + // eslint-disable-next-line @typescript-eslint/camelcase + command.__is_reject_overwritten = true; + const reject = command.reject; + command.reject = function (err) { + const partialTry = tryConnection.bind(null, true); + _this.handleError(err, ttl, { + moved: function (slot, key) { + debug("command %s is moved to %s", command.name, key); + targetSlot = Number(slot); + if (_this.slots[slot]) { + _this.slots[slot][0] = key; + } + else { + _this.slots[slot] = [key]; + } + _this.connectionPool.findOrCreate(_this.natMapper(key)); + tryConnection(); + debug("refreshing slot caches... (triggered by MOVED error)"); + _this.refreshSlotsCache(); + }, + ask: function (slot, key) { + debug("command %s is required to ask %s:%s", command.name, key); + const mapped = _this.natMapper(key); + _this.connectionPool.findOrCreate(mapped); + tryConnection(false, `${mapped.host}:${mapped.port}`); + }, + tryagain: partialTry, + clusterDown: partialTry, + connectionClosed: partialTry, + maxRedirections: function (redirectionError) { + reject.call(command, redirectionError); + }, + defaults: function () { + reject.call(command, err); + }, + }); + }; } - }, - - _functionToNumber: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - var convertedValue; - if (typeName === TYPE_NUMBER) { - return resolvedArgs[0]; - } else if (typeName === TYPE_STRING) { - convertedValue = +resolvedArgs[0]; - if (!isNaN(convertedValue)) { - return convertedValue; + tryConnection(); + function tryConnection(random, asking) { + if (_this.status === "end") { + command.reject(new redis_errors_1.AbortError("Cluster is ended.")); + return; } - } - return null; - }, - - _functionNotNull: function(resolvedArgs) { - for (var i = 0; i < resolvedArgs.length; i++) { - if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { - return resolvedArgs[i]; + let redis; + if (_this.status === "ready" || command.name === "cluster") { + if (node && node.redis) { + redis = node.redis; + } + else if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", command.name) || + command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", command.name)) { + redis = _this.subscriber.getInstance(); + if (!redis) { + command.reject(new redis_errors_1.AbortError("No subscriber for the cluster")); + return; + } + } + else { + if (!random) { + if (typeof targetSlot === "number" && _this.slots[targetSlot]) { + const nodeKeys = _this.slots[targetSlot]; + if (typeof to === "function") { + const nodes = nodeKeys.map(function (key) { + return _this.connectionPool.getInstanceByKey(key); + }); + redis = to(nodes, command); + if (Array.isArray(redis)) { + redis = utils_2.sample(redis); + } + if (!redis) { + redis = nodes[0]; + } + } + else { + let key; + if (to === "all") { + key = utils_2.sample(nodeKeys); + } + else if (to === "slave" && nodeKeys.length > 1) { + key = utils_2.sample(nodeKeys, 1); + } + else { + key = nodeKeys[0]; + } + redis = _this.connectionPool.getInstanceByKey(key); + } + } + if (asking) { + redis = _this.connectionPool.getInstanceByKey(asking); + redis.asking(); + } + } + if (!redis) { + redis = + (typeof to === "function" + ? null + : _this.connectionPool.getSampleInstance(to)) || + _this.connectionPool.getSampleInstance("all"); + } + } + if (node && !node.redis) { + node.redis = redis; + } + } + if (redis) { + redis.sendCommand(command, stream); + } + else if (_this.options.enableOfflineQueue) { + _this.offlineQueue.push({ + command: command, + stream: stream, + node: node, + }); + } + else { + command.reject(new Error("Cluster isn't ready and enableOfflineQueue options is false")); } } - return null; - }, - - _functionSort: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - sortedArray.sort(); - return sortedArray; - }, - - _functionSortBy: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - if (sortedArray.length === 0) { - return sortedArray; - } - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[1]; - var requiredType = this._getTypeName( - interpreter.visit(exprefNode, sortedArray[0])); - if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { - throw new Error("TypeError"); + return command.promise; + } + handleError(error, ttl, handlers) { + if (typeof ttl.value === "undefined") { + ttl.value = this.options.maxRedirections; } - var that = this; - // In order to get a stable sort out of an unstable - // sort algorithm, we decorate/sort/undecorate (DSU) - // by creating a new list of [index, element] pairs. - // In the cmp function, if the evaluated elements are - // equal, then the index will be used as the tiebreaker. - // After the decorated list has been sorted, it will be - // undecorated to extract the original elements. - var decorated = []; - for (var i = 0; i < sortedArray.length; i++) { - decorated.push([i, sortedArray[i]]); + else { + ttl.value -= 1; } - decorated.sort(function(a, b) { - var exprA = interpreter.visit(exprefNode, a[1]); - var exprB = interpreter.visit(exprefNode, b[1]); - if (that._getTypeName(exprA) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprA)); - } else if (that._getTypeName(exprB) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprB)); - } - if (exprA > exprB) { - return 1; - } else if (exprA < exprB) { - return -1; - } else { - // If they're equal compare the items by their - // order to maintain relative order of equal keys - // (i.e. to get a stable sort). - return a[0] - b[0]; - } - }); - // Undecorate: extract out the original list elements. - for (var j = 0; j < decorated.length; j++) { - sortedArray[j] = decorated[j][1]; + if (ttl.value <= 0) { + handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); + return; } - return sortedArray; - }, - - _functionMaxBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var maxNumber = -Infinity; - var maxRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current > maxNumber) { - maxNumber = current; - maxRecord = resolvedArray[i]; + const errv = error.message.split(" "); + if (errv[0] === "MOVED" || errv[0] === "ASK") { + handlers[errv[0] === "MOVED" ? "moved" : "ask"](errv[1], errv[2]); } - } - return maxRecord; - }, - - _functionMinBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var minNumber = Infinity; - var minRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current < minNumber) { - minNumber = current; - minRecord = resolvedArray[i]; + else if (errv[0] === "TRYAGAIN") { + this.delayQueue.push("tryagain", handlers.tryagain, { + timeout: this.options.retryDelayOnTryAgain, + }); } - } - return minRecord; - }, - - createKeyFunction: function(exprefNode, allowedTypes) { - var that = this; - var interpreter = this._interpreter; - var keyFunc = function(x) { - var current = interpreter.visit(exprefNode, x); - if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { - var msg = "TypeError: expected one of " + allowedTypes + - ", received " + that._getTypeName(current); - throw new Error(msg); + else if (errv[0] === "CLUSTERDOWN" && + this.options.retryDelayOnClusterDown > 0) { + this.delayQueue.push("clusterdown", handlers.connectionClosed, { + timeout: this.options.retryDelayOnClusterDown, + callback: this.refreshSlotsCache.bind(this), + }); + } + else if (error.message === utils_2.CONNECTION_CLOSED_ERROR_MSG && + this.options.retryDelayOnFailover > 0 && + this.status === "ready") { + this.delayQueue.push("failover", handlers.connectionClosed, { + timeout: this.options.retryDelayOnFailover, + callback: this.refreshSlotsCache.bind(this), + }); + } + else { + handlers.defaults(); } - return current; - }; - return keyFunc; - } - - }; - - function compile(stream) { - var parser = new Parser(); - var ast = parser.parse(stream); - return ast; - } - - function tokenize(stream) { - var lexer = new Lexer(); - return lexer.tokenize(stream); - } - - function search(data, expression) { - var parser = new Parser(); - // This needs to be improved. Both the interpreter and runtime depend on - // each other. The runtime needs the interpreter to support exprefs. - // There's likely a clean way to avoid the cyclic dependency. - var runtime = new Runtime(); - var interpreter = new TreeInterpreter(runtime); - runtime._interpreter = interpreter; - var node = parser.parse(expression); - return interpreter.search(node, data); - } - - exports.tokenize = tokenize; - exports.compile = compile; - exports.search = search; - exports.strictDeepEqual = strictDeepEqual; -})( false ? 0 : exports); - - -/***/ }), - -/***/ 21917: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - - -var yaml = __nccwpck_require__(40916); - - -module.exports = yaml; - - -/***/ }), - -/***/ 40916: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - - -var loader = __nccwpck_require__(45190); -var dumper = __nccwpck_require__(73034); - - -function deprecated(name) { - return function () { - throw new Error('Function ' + name + ' is deprecated and cannot be used.'); - }; -} - - -module.exports.Type = __nccwpck_require__(30967); -module.exports.Schema = __nccwpck_require__(66514); -module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(66037); -module.exports.JSON_SCHEMA = __nccwpck_require__(1571); -module.exports.CORE_SCHEMA = __nccwpck_require__(92183); -module.exports.DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); -module.exports.DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.safeLoad = loader.safeLoad; -module.exports.safeLoadAll = loader.safeLoadAll; -module.exports.dump = dumper.dump; -module.exports.safeDump = dumper.safeDump; -module.exports.YAMLException = __nccwpck_require__(65199); - -// Deprecated schema names from JS-YAML 2.0.x -module.exports.MINIMAL_SCHEMA = __nccwpck_require__(66037); -module.exports.SAFE_SCHEMA = __nccwpck_require__(48949); -module.exports.DEFAULT_SCHEMA = __nccwpck_require__(56874); - -// Deprecated functions from JS-YAML 1.x.x -module.exports.scan = deprecated('scan'); -module.exports.parse = deprecated('parse'); -module.exports.compose = deprecated('compose'); -module.exports.addConstructor = deprecated('addConstructor'); - - -/***/ }), - -/***/ 59136: -/***/ ((module) => { - -"use strict"; - - - -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} - - -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} - - -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - - return [ sequence ]; -} - - -function extend(target, source) { - var index, length, key, sourceKeys; - - if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; } - } - - return target; -} - - -function repeat(string, count) { - var result = '', cycle; - - for (cycle = 0; cycle < count; cycle += 1) { - result += string; - } - - return result; -} - - -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} - - -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; - - -/***/ }), - -/***/ 73034: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/*eslint-disable no-use-before-define*/ - -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); -var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); - -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_EQUALS = 0x3D; /* = */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; - -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; - - if (map === null) return {}; - - result = {}; - keys = Object.keys(map); - - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); - - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); + getInfoFromNode(redis, callback) { + if (!redis) { + return callback(new Error("Node is disconnected")); + } + // Use a duplication of the connection to avoid + // timeouts when the connection is in the blocking + // mode (e.g. waiting for BLPOP). + const duplicatedConnection = redis.duplicate({ + enableOfflineQueue: true, + enableReadyCheck: false, + retryStrategy: null, + connectionName: "ioredisClusterRefresher", + }); + // Ignore error events since we will handle + // exceptions for the CLUSTER SLOTS command. + duplicatedConnection.on("error", utils_1.noop); + duplicatedConnection.cluster("slots", utils_2.timeout((err, result) => { + duplicatedConnection.disconnect(); + if (err) { + return callback(err); + } + if (this.status === "disconnecting" || + this.status === "close" || + this.status === "end") { + debug("ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s", result.length, this.status); + callback(); + return; + } + const nodes = []; + debug("cluster slots result count: %d", result.length); + for (let i = 0; i < result.length; ++i) { + const items = result[i]; + const slotRangeStart = items[0]; + const slotRangeEnd = items[1]; + const keys = []; + for (let j = 2; j < items.length; j++) { + if (!items[j][0]) { + continue; + } + items[j] = this.natMapper({ host: items[j][0], port: items[j][1] }); + items[j].readOnly = j !== 2; + nodes.push(items[j]); + keys.push(items[j].host + ":" + items[j].port); + } + debug("cluster slots result [%d]: slots %d~%d served by %s", i, slotRangeStart, slotRangeEnd, keys); + for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) { + this.slots[slot] = keys; + } + } + this.connectionPool.reset(nodes); + callback(); + }, this.options.slotsRefreshTimeout)); } - type = schema.compiledTypeMap['fallback'][tag]; - - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; + invokeReadyDelayedCallbacks(err) { + for (const c of this._readyDelayedCallbacks) { + process.nextTick(c, err); + } + this._readyDelayedCallbacks = []; } - - result[tag] = style; - } - - return result; -} - -function encodeHex(character) { - var string, handle, length; - - string = character.toString(16).toUpperCase(); - - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } - - return '\\' + handle + common.repeat('0', length - string.length) + string; -} - -function State(options) { - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; - - this.tag = null; - this.result = ''; - - this.duplicates = []; - this.usedDuplicates = null; -} - -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; - - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; + /** + * Check whether Cluster is able to process commands + * + * @param {Function} callback + * @private + */ + readyCheck(callback) { + this.cluster("info", function (err, res) { + if (err) { + return callback(err); + } + if (typeof res !== "string") { + return callback(); + } + let state; + const lines = res.split("\r\n"); + for (let i = 0; i < lines.length; ++i) { + const parts = lines[i].split(":"); + if (parts[0] === "cluster_state") { + state = parts[1]; + break; + } + } + if (state === "fail") { + debug("cluster state not ok (%s)", state); + callback(null, state); + } + else { + callback(); + } + }); + } + dnsLookup(hostname) { + return new Promise((resolve, reject) => { + this.options.dnsLookup(hostname, (err, address) => { + if (err) { + debug("failed to resolve hostname %s to IP: %s", hostname, err.message); + reject(err); + } + else { + debug("resolved hostname %s to IP %s", hostname, address); + resolve(address); + } + }); + }); + } + /** + * Normalize startup nodes, and resolving hostnames to IPs. + * + * This process happens every time when #connect() is called since + * #startupNodes and DNS records may chanage. + * + * @private + * @returns {Promise} + */ + resolveStartupNodeHostnames() { + if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) { + return Promise.reject(new Error("`startupNodes` should contain at least one node.")); + } + const startupNodes = util_1.normalizeNodeOptions(this.startupNodes); + const hostnames = util_1.getUniqueHostnamesFromOptions(startupNodes); + if (hostnames.length === 0) { + return Promise.resolve(startupNodes); + } + return Promise.all(hostnames.map((hostname) => this.dnsLookup(hostname))).then((ips) => { + const hostnameToIP = utils_2.zipMap(hostnames, ips); + return startupNodes.map((node) => hostnameToIP.has(node.host) + ? Object.assign({}, node, { host: hostnameToIP.get(node.host) }) + : node); + }); } - - if (line.length && line !== '\n') result += ind; - - result += line; - } - - return result; -} - -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); } +Object.getOwnPropertyNames(commander_1.default.prototype).forEach((name) => { + if (!Cluster.prototype.hasOwnProperty(name)) { + Cluster.prototype[name] = commander_1.default.prototype[name]; + } +}); +const scanCommands = [ + "sscan", + "hscan", + "zscan", + "sscanBuffer", + "hscanBuffer", + "zscanBuffer", +]; +scanCommands.forEach((command) => { + Cluster.prototype[command + "Stream"] = function (key, options) { + return new ScanStream_1.default(utils_1.defaults({ + objectMode: true, + key: key, + redis: this, + command: command, + }, options)); + }; +}); +__nccwpck_require__(14645).addTransactionSupport(Cluster.prototype); +exports.default = Cluster; -function testImplicitResolving(state, str) { - var index, length, type; - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; +/***/ }), - if (type.resolve(str)) { - return true; - } - } +/***/ 94582: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return false; -} +"use strict"; -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const net_1 = __nccwpck_require__(11631); +function getNodeKey(node) { + node.port = node.port || 6379; + node.host = node.host || "127.0.0.1"; + return node.host + ":" + node.port; } - -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) - || (0x10000 <= c && c <= 0x10FFFF); +exports.getNodeKey = getNodeKey; +function nodeKeyToRedisOptions(nodeKey) { + const portIndex = nodeKey.lastIndexOf(":"); + if (portIndex === -1) { + throw new Error(`Invalid node key ${nodeKey}`); + } + return { + host: nodeKey.slice(0, portIndex), + port: Number(nodeKey.slice(portIndex + 1)), + }; } - -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// [24] b-line-feed ::= #xA /* LF */ -// [25] b-carriage-return ::= #xD /* CR */ -// [3] c-byte-order-mark ::= #xFEFF -function isNsChar(c) { - return isPrintable(c) && !isWhitespace(c) - // byte-order-mark - && c !== 0xFEFF - // b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; +exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; +function normalizeNodeOptions(nodes) { + return nodes.map((node) => { + const options = {}; + if (typeof node === "object") { + Object.assign(options, node); + } + else if (typeof node === "string") { + Object.assign(options, utils_1.parseURL(node)); + } + else if (typeof node === "number") { + options.port = node; + } + else { + throw new Error("Invalid argument " + node); + } + if (typeof options.port === "string") { + options.port = parseInt(options.port, 10); + } + // Cluster mode only support db 0 + delete options.db; + if (!options.port) { + options.port = 6379; + } + if (!options.host) { + options.host = "127.0.0.1"; + } + return options; + }); } - -// Simplified test for values allowed after the first character in plain style. -function isPlainSafe(c, prev) { - // Uses a subset of nb-char - c-flow-indicator - ":" - "#" - // where nb-char ::= c-printable - b-char - c-byte-order-mark. - return isPrintable(c) && c !== 0xFEFF - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // - ":" - "#" - // /* An ns-char preceding */ "#" - && c !== CHAR_COLON - && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +exports.normalizeNodeOptions = normalizeNodeOptions; +function getUniqueHostnamesFromOptions(nodes) { + const uniqueHostsMap = {}; + nodes.forEach((node) => { + uniqueHostsMap[node.host] = true; + }); + return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); } +exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - return isPrintable(c) && c !== 0xFEFF - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); -} +/***/ }), -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; +/***/ 90803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { - var i; - var char, prev_char; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(string.charCodeAt(0)) - && !isWhitespace(string.charCodeAt(string.length - 1)); +"use strict"; - if (singleLineOnly) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const commands = __nccwpck_require__(98020); +const calculateSlot = __nccwpck_require__(48481); +const standard_as_callback_1 = __nccwpck_require__(91543); +const utils_1 = __nccwpck_require__(94832); +const lodash_1 = __nccwpck_require__(20961); +const promiseContainer_1 = __nccwpck_require__(71475); +/** + * Command instance + * + * It's rare that you need to create a Command instance yourself. + * + * @export + * @class Command + * + * @example + * ```js + * var infoCommand = new Command('info', null, function (err, result) { + * console.log('result', result); + * }); + * + * redis.sendCommand(infoCommand); + * + * // When no callback provided, Command instance will have a `promise` property, + * // which will resolve/reject with the result of the command. + * var getCommand = new Command('get', ['foo']); + * getCommand.promise.then(function (result) { + * console.log('result', result); + * }); + * ``` + * @see {@link Redis#sendCommand} which can send a Command instance to Redis + */ +class Command { + /** + * Creates an instance of Command. + * @param {string} name Command name + * @param {(Array)} [args=[]] An array of command arguments + * @param {ICommandOptions} [options={}] + * @param {CallbackFunction} [callback] The callback that handles the response. + * If omit, the response will be handled via Promise + * @memberof Command + */ + constructor(name, args = [], options = {}, callback) { + this.name = name; + this.transformed = false; + this.isCustomCommand = false; + this.inTransaction = false; + this.replyEncoding = options.replyEncoding; + this.errorStack = options.errorStack; + this.args = lodash_1.flatten(args); + this.callback = callback; + this.initPromise(); + if (options.keyPrefix) { + this._iterateKeys((key) => options.keyPrefix + key); + } + if (options.readOnly) { + this.isReadOnly = true; + } } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; + static getFlagMap() { + if (!this.flagMap) { + this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { + map[flagName] = {}; + Command.FLAGS[flagName].forEach((commandName) => { + map[flagName][commandName] = true; + }); + return map; + }, {}); + } + return this.flagMap; + } + /** + * Check whether the command has the flag + * + * @param {string} flagName + * @param {string} commandName + * @return {boolean} + */ + static checkFlag(flagName, commandName) { + return !!this.getFlagMap()[flagName][commandName]; + } + static setArgumentTransformer(name, func) { + this._transformer.argument[name] = func; + } + static setReplyTransformer(name, func) { + this._transformer.reply[name] = func; + } + initPromise() { + const Promise = promiseContainer_1.get(); + const promise = new Promise((resolve, reject) => { + if (!this.transformed) { + this.transformed = true; + const transformer = Command._transformer.argument[this.name]; + if (transformer) { + this.args = transformer(this.args); + } + this.stringifyArguments(); + } + this.resolve = this._convertValue(resolve); + if (this.errorStack) { + this.reject = (err) => { + reject(utils_1.optimizeErrorStack(err, this.errorStack, __dirname)); + }; + } + else { + this.reject = reject; + } + }); + this.promise = standard_as_callback_1.default(promise, this.callback); + } + getSlot() { + if (typeof this.slot === "undefined") { + const key = this.getKeys()[0]; + this.slot = key == null ? null : calculateSlot(key); + } + return this.slot; + } + getKeys() { + return this._iterateKeys(); + } + /** + * Iterate through the command arguments that are considered keys. + * + * @param {Function} [transform=(key) => key] The transformation that should be applied to + * each key. The transformations will persist. + * @returns {string[]} The keys of the command. + * @memberof Command + */ + _iterateKeys(transform = (key) => key) { + if (typeof this.keys === "undefined") { + this.keys = []; + if (commands.exists(this.name)) { + const keyIndexes = commands.getKeyIndexes(this.name, this.args); + for (const index of keyIndexes) { + this.args[index] = transform(this.args[index]); + this.keys.push(this.args[index]); + } + } + } + return this.keys; + } + /** + * Convert command to writable buffer or string + * + * @return {string|Buffer} + * @see {@link Redis#sendCommand} + * @public + */ + toWritable() { + let bufferMode = false; + for (const arg of this.args) { + if (arg instanceof Buffer) { + bufferMode = true; + break; + } + } + let result; + const commandStr = "*" + + (this.args.length + 1) + + "\r\n$" + + Buffer.byteLength(this.name) + + "\r\n" + + this.name + + "\r\n"; + if (bufferMode) { + const buffers = new MixedBuffers(); + buffers.push(commandStr); + for (const arg of this.args) { + if (arg instanceof Buffer) { + if (arg.length === 0) { + buffers.push("$0\r\n\r\n"); + } + else { + buffers.push("$" + arg.length + "\r\n"); + buffers.push(arg); + buffers.push("\r\n"); + } + } + else { + buffers.push("$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"); + } + } + result = buffers.toBuffer(); + } + else { + result = commandStr; + for (const arg of this.args) { + result += + "$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"; + } + } + return result; + } + stringifyArguments() { + for (let i = 0; i < this.args.length; ++i) { + const arg = this.args[i]; + if (!(arg instanceof Buffer) && typeof arg !== "string") { + this.args[i] = utils_1.toArg(arg); + } + } + } + /** + * Convert the value from buffer to the target encoding. + * + * @private + * @param {Function} resolve The resolve function of the Promise + * @returns {Function} A function to transform and resolve a value + * @memberof Command + */ + _convertValue(resolve) { + return (value) => { + try { + resolve(this.transformReply(value)); + } + catch (err) { + this.reject(err); + } + return this.promise; + }; + } + /** + * Convert buffer/buffer[] to string/string[], + * and apply reply transformer. + * + * @memberof Command + */ + transformReply(result) { + if (this.replyEncoding) { + result = utils_1.convertBufferToString(result, this.replyEncoding); + } + const transformer = Command._transformer.reply[this.name]; + if (transformer) { + result = transformer(result); } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); + return result; } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - return plain && !testAmbiguousType(string) - ? STYLE_PLAIN : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } - -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey) { - state.dump = (function () { - if (string.length === 0) { - return "''"; +exports.default = Command; +Command.FLAGS = { + VALID_IN_SUBSCRIBER_MODE: [ + "subscribe", + "psubscribe", + "unsubscribe", + "punsubscribe", + "ping", + "quit", + ], + VALID_IN_MONITOR_MODE: ["monitor", "auth"], + ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], + EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], + WILL_DISCONNECT: ["quit"], +}; +Command._transformer = { + argument: {}, + reply: {}, +}; +const msetArgumentTransformer = function (args) { + if (args.length === 1) { + if (typeof Map !== "undefined" && args[0] instanceof Map) { + return utils_1.convertMapToArray(args[0]); + } + if (typeof args[0] === "object" && args[0] !== null) { + return utils_1.convertObjectToArray(args[0]); + } } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; + return args; +}; +Command.setArgumentTransformer("mset", msetArgumentTransformer); +Command.setArgumentTransformer("msetnx", msetArgumentTransformer); +Command.setArgumentTransformer("hmset", function (args) { + if (args.length === 2) { + if (typeof Map !== "undefined" && args[1] instanceof Map) { + return [args[0]].concat(utils_1.convertMapToArray(args[1])); + } + if (typeof args[1] === "object" && args[1] !== null) { + return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + } } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); + return args; +}); +Command.setReplyTransformer("hgetall", function (result) { + if (Array.isArray(result)) { + const obj = {}; + for (let i = 0; i < result.length; i += 2) { + obj[result[i]] = result[i + 1]; + } + return obj; } - - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); + return result; +}); +Command.setArgumentTransformer("hset", function (args) { + if (args.length === 2) { + if (typeof Map !== "undefined" && args[1] instanceof Map) { + return [args[0]].concat(utils_1.convertMapToArray(args[1])); + } + if (typeof args[1] === "object" && args[1] !== null) { + return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + } } - }()); -} - -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); - - return indentIndicator + chomp + '\n'; -} - -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} - -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; - - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } - - return result; -} - -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; - - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; - - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 + return args; +}); +class MixedBuffers { + constructor() { + this.length = 0; + this.items = []; } - curr = next; - } - - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } - - return result.slice(1); // drop extra \n joiner -} - -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char, nextChar; - var escapeSeq; - - for (var i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). - if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { - nextChar = string.charCodeAt(i + 1); - if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { - // Combine the surrogate pair and store it escaped. - result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); - // Advance index one extra since we already used that char here. - i++; continue; - } + push(x) { + this.length += Buffer.byteLength(x); + this.items.push(x); } - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); - } - - return result; -} - -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level, object[index], false, false)) { - if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; + toBuffer() { + const result = Buffer.allocUnsafe(this.length); + let offset = 0; + for (const item of this.items) { + const length = Buffer.byteLength(item); + Buffer.isBuffer(item) + ? item.copy(result, offset) + : result.write(item, offset, length); + offset += length; + } + return result; } - } - - state.tag = _tag; - state.dump = '[' + _result + ']'; } -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length; - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level + 1, object[index], true, true)) { - if (!compact || index !== 0) { - _result += generateNextLine(state, level); - } +/***/ }), - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } +/***/ 33642: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _result += state.dump; - } - } +"use strict"; - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lodash_1 = __nccwpck_require__(20961); +const command_1 = __nccwpck_require__(90803); +const script_1 = __nccwpck_require__(88540); +const PromiseContainer = __nccwpck_require__(71475); +const standard_as_callback_1 = __nccwpck_require__(91543); +const autoPipelining_1 = __nccwpck_require__(97873); +const DROP_BUFFER_SUPPORT_ERROR = "*Buffer methods are not available " + + 'because "dropBufferSupport" option is enabled.' + + "Refer to https://github.com/luin/ioredis/wiki/Improve-Performance for more details."; +/** + * Commander + * + * This is the base class of Redis, Redis.Cluster and Pipeline + * + * @param {boolean} [options.showFriendlyErrorStack=false] - Whether to show a friendly error stack. + * Will decrease the performance significantly. + * @constructor + */ +function Commander() { + this.options = lodash_1.defaults({}, this.options || {}, { + showFriendlyErrorStack: false, + }); + this.scriptsSet = {}; } - -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - - pairBuffer = ''; - if (index !== 0) pairBuffer += ', '; - - if (state.condenseFlow) pairBuffer += '"'; - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. +exports.default = Commander; +const commands = __nccwpck_require__(98020).list.filter(function (command) { + return command !== "monitor"; +}); +commands.push("sentinel"); +/** + * Return supported builtin commands + * + * @return {string[]} command list + * @public + */ +Commander.prototype.getBuiltinCommands = function () { + return commands.slice(0); +}; +/** + * Create a builtin command + * + * @param {string} commandName - command name + * @return {object} functions + * @public + */ +Commander.prototype.createBuiltinCommand = function (commandName) { + return { + string: generateFunction(commandName, "utf8"), + buffer: generateFunction(commandName, null), + }; +}; +commands.forEach(function (commandName) { + Commander.prototype[commandName] = generateFunction(commandName, "utf8"); + Commander.prototype[commandName + "Buffer"] = generateFunction(commandName, null); +}); +Commander.prototype.call = generateFunction("utf8"); +Commander.prototype.callBuffer = generateFunction(null); +// eslint-disable-next-line @typescript-eslint/camelcase +Commander.prototype.send_command = Commander.prototype.call; +/** + * Define a custom command using lua script + * + * @param {string} name - the command name + * @param {object} definition + * @param {string} definition.lua - the lua code + * @param {number} [definition.numberOfKeys=null] - the number of keys. + * @param {boolean} [definition.readOnly=false] - force this script to be readonly so it executes on slaves as well. + * If omit, you have to pass the number of keys as the first argument every time you invoke the command + */ +Commander.prototype.defineCommand = function (name, definition) { + const script = new script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly); + this.scriptsSet[name] = script; + this[name] = generateScriptingFunction(name, script, "utf8"); + this[name + "Buffer"] = generateScriptingFunction(name, script, null); +}; +/** + * Send a command + * + * @abstract + * @public + */ +Commander.prototype.sendCommand = function () { }; +function generateFunction(_commandName, _encoding) { + if (typeof _encoding === "undefined") { + _encoding = _commandName; + _commandName = null; } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = '{' + _result + '}'; + return function (...args) { + const commandName = _commandName || args.shift(); + let callback = args[args.length - 1]; + if (typeof callback === "function") { + args.pop(); + } + else { + callback = undefined; + } + const options = { + errorStack: this.options.showFriendlyErrorStack + ? new Error().stack + : undefined, + keyPrefix: this.options.keyPrefix, + replyEncoding: _encoding, + }; + if (this.options.dropBufferSupport && !_encoding) { + return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); + } + // No auto pipeline, use regular command sending + if (!autoPipelining_1.shouldUseAutoPipelining(this, commandName)) { + return this.sendCommand(new command_1.default(commandName, args, options, callback)); + } + // Create a new pipeline and make sure it's scheduled + return autoPipelining_1.executeWithAutoPipelining(this, commandName, args, callback); + }; +} +function generateScriptingFunction(name, script, encoding) { + return function () { + let length = arguments.length; + const lastArgIndex = length - 1; + let callback = arguments[lastArgIndex]; + if (typeof callback !== "function") { + callback = undefined; + } + else { + length = lastArgIndex; + } + const args = new Array(length); + for (let i = 0; i < length; i++) { + args[i] = arguments[i]; + } + let options; + if (this.options.dropBufferSupport) { + if (!encoding) { + return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); + } + options = { replyEncoding: null }; + } + else { + options = { replyEncoding: encoding }; + } + if (this.options.showFriendlyErrorStack) { + options.errorStack = new Error().stack; + } + // No auto pipeline, use regular command sending + if (!autoPipelining_1.shouldUseAutoPipelining(this, name)) { + return script.execute(this, args, options, callback); + } + // Create a new pipeline and make sure it's scheduled + return autoPipelining_1.executeWithAutoPipelining(this, name, args, callback); + }; } -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; - - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); +/***/ }), - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } +/***/ 72712: +/***/ ((__unused_webpack_module, exports) => { - pairBuffer += state.dump; +"use strict"; - if (explicitPair) { - pairBuffer += generateNextLine(state, level); +Object.defineProperty(exports, "__esModule", ({ value: true })); +class AbstractConnector { + constructor() { + this.connecting = false; } - - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. + check(info) { + return true; } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; + disconnect() { + this.connecting = false; + if (this.stream) { + this.stream.end(); + } } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. } +exports.default = AbstractConnector; -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - - typeList = explicit ? state.explicitTypes : state.implicitTypes; - - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { +/***/ }), - state.tag = explicit ? type.tag : '?'; +/***/ 72225: +/***/ ((__unused_webpack_module, exports) => { - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; +"use strict"; - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isSentinelEql(a, b) { + return ((a.host || "127.0.0.1") === (b.host || "127.0.0.1") && + (a.port || 26379) === (b.port || 26379)); +} +class SentinelIterator { + constructor(sentinels) { + this.cursor = 0; + this.sentinels = sentinels.slice(0); + } + next() { + const done = this.cursor >= this.sentinels.length; + return { done, value: done ? undefined : this.sentinels[this.cursor++] }; + } + reset(moveCurrentEndpointToFirst) { + if (moveCurrentEndpointToFirst && + this.sentinels.length > 1 && + this.cursor !== 1) { + this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1)); } - - state.dump = _result; - } - - return true; + this.cursor = 0; + } + add(sentinel) { + for (let i = 0; i < this.sentinels.length; i++) { + if (isSentinelEql(sentinel, this.sentinels[i])) { + return false; + } + } + this.sentinels.push(sentinel); + return true; + } + toString() { + return `${JSON.stringify(this.sentinels)} @${this.cursor}`; } - } - - return false; } +exports.default = SentinelIterator; -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); - } - - var type = _toString.call(state.dump); - - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; +/***/ }), - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } +/***/ 10379: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } +"use strict"; - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __nccwpck_require__(11631); +const utils_1 = __nccwpck_require__(94832); +const tls_1 = __nccwpck_require__(4016); +const StandaloneConnector_1 = __nccwpck_require__(8774); +const SentinelIterator_1 = __nccwpck_require__(72225); +exports.SentinelIterator = SentinelIterator_1.default; +const AbstractConnector_1 = __nccwpck_require__(72712); +const redis_1 = __nccwpck_require__(83609); +const debug = utils_1.Debug("SentinelConnector"); +class SentinelConnector extends AbstractConnector_1.default { + constructor(options) { + super(); + this.options = options; + if (!this.options.sentinels.length) { + throw new Error("Requires at least one sentinel to connect to."); + } + if (!this.options.name) { + throw new Error("Requires the name of master."); + } + this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels); } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; + check(info) { + const roleMatches = !info.role || this.options.role === info.role; + if (!roleMatches) { + debug("role invalid, expected %s, but got %s", this.options.role, info.role); + // Start from the next item. + // Note that `reset` will move the cursor to the previous element, + // so we advance two steps here. + this.sentinelIterator.next(); + this.sentinelIterator.next(); + this.sentinelIterator.reset(true); } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + return roleMatches; + } + connect(eventEmitter) { + this.connecting = true; + this.retryAttempts = 0; + let lastError; + const connectToNext = () => new Promise((resolve, reject) => { + const endpoint = this.sentinelIterator.next(); + if (endpoint.done) { + this.sentinelIterator.reset(false); + const retryDelay = typeof this.options.sentinelRetryStrategy === "function" + ? this.options.sentinelRetryStrategy(++this.retryAttempts) + : null; + let errorMsg = typeof retryDelay !== "number" + ? "All sentinels are unreachable and retry is disabled." + : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`; + if (lastError) { + errorMsg += ` Last error: ${lastError.message}`; + } + debug(errorMsg); + const error = new Error(errorMsg); + if (typeof retryDelay === "number") { + setTimeout(() => { + resolve(connectToNext()); + }, retryDelay); + eventEmitter("error", error); + } + else { + reject(error); + } + return; + } + this.resolve(endpoint.value, (err, resolved) => { + if (!this.connecting) { + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return; + } + if (resolved) { + debug("resolved: %s:%s", resolved.host, resolved.port); + if (this.options.enableTLSForSentinelMode && this.options.tls) { + Object.assign(resolved, this.options.tls); + this.stream = tls_1.connect(resolved); + } + else { + this.stream = net_1.createConnection(resolved); + } + this.sentinelIterator.reset(true); + resolve(this.stream); + } + else { + const endpointAddress = endpoint.value.host + ":" + endpoint.value.port; + const errorMsg = err + ? "failed to connect to sentinel " + + endpointAddress + + " because " + + err.message + : "connected to sentinel " + + endpointAddress + + " successfully, but got an invalid reply: " + + resolved; + debug(errorMsg); + eventEmitter("sentinelError", new Error(errorMsg)); + if (err) { + lastError = err; + } + resolve(connectToNext()); + } + }); + }); + return connectToNext(); + } + updateSentinels(client, callback) { + if (!this.options.updateSentinels) { + return callback(null); } - } - } else if (type === '[object Array]') { - var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; - if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, arrayLevel, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; + client.sentinel("sentinels", this.options.name, (err, result) => { + if (err) { + client.disconnect(); + return callback(err); + } + if (!Array.isArray(result)) { + return callback(null); + } + result + .map(utils_1.packObject) + .forEach((sentinel) => { + const flags = sentinel.flags ? sentinel.flags.split(",") : []; + if (flags.indexOf("disconnected") === -1 && + sentinel.ip && + sentinel.port) { + const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel)); + if (this.sentinelIterator.add(endpoint)) { + debug("adding sentinel %s:%s", endpoint.host, endpoint.port); + } + } + }); + debug("Updated internal sentinels: %s", this.sentinelIterator); + callback(null); + }); + } + resolveMaster(client, callback) { + client.sentinel("get-master-addr-by-name", this.options.name, (err, result) => { + if (err) { + client.disconnect(); + return callback(err); + } + this.updateSentinels(client, (err) => { + client.disconnect(); + if (err) { + return callback(err); + } + callback(null, this.sentinelNatResolve(Array.isArray(result) + ? { host: result[0], port: Number(result[1]) } + : null)); + }); + }); + } + resolveSlave(client, callback) { + client.sentinel("slaves", this.options.name, (err, result) => { + client.disconnect(); + if (err) { + return callback(err); + } + if (!Array.isArray(result)) { + return callback(null, null); + } + const availableSlaves = result + .map(utils_1.packObject) + .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)); + callback(null, this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves))); + }); + } + sentinelNatResolve(item) { + if (!item || !this.options.natMap) + return item; + return this.options.natMap[`${item.host}:${item.port}`] || item; + } + resolve(endpoint, callback) { + const client = new redis_1.default({ + port: endpoint.port || 26379, + host: endpoint.host, + username: this.options.sentinelUsername || null, + password: this.options.sentinelPassword || null, + family: endpoint.family || + (StandaloneConnector_1.isIIpcConnectionOptions(this.options) + ? undefined + : this.options.family), + tls: this.options.sentinelTLS, + retryStrategy: null, + enableReadyCheck: false, + connectTimeout: this.options.connectTimeout, + dropBufferSupport: true, + }); + // ignore the errors since resolve* methods will handle them + client.on("error", noop); + if (this.options.role === "slave") { + this.resolveSlave(client, callback); } - } else { - writeFlowSequence(state, arrayLevel, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + else { + this.resolveMaster(client, callback); } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey); - } - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); } - - if (state.tag !== null && state.tag !== '?') { - state.dump = '!<' + state.tag + '> ' + state.dump; +} +exports.default = SentinelConnector; +function selectPreferredSentinel(availableSlaves, preferredSlaves) { + if (availableSlaves.length === 0) { + return null; } - } - - return true; + let selectedSlave; + if (typeof preferredSlaves === "function") { + selectedSlave = preferredSlaves(availableSlaves); + } + else if (preferredSlaves !== null && typeof preferredSlaves === "object") { + const preferredSlavesArray = Array.isArray(preferredSlaves) + ? preferredSlaves + : [preferredSlaves]; + // sort by priority + preferredSlavesArray.sort((a, b) => { + // default the priority to 1 + if (!a.prio) { + a.prio = 1; + } + if (!b.prio) { + b.prio = 1; + } + // lowest priority first + if (a.prio < b.prio) { + return -1; + } + if (a.prio > b.prio) { + return 1; + } + return 0; + }); + // loop over preferred slaves and return the first match + for (let p = 0; p < preferredSlavesArray.length; p++) { + for (let a = 0; a < availableSlaves.length; a++) { + const slave = availableSlaves[a]; + if (slave.ip === preferredSlavesArray[p].ip) { + if (slave.port === preferredSlavesArray[p].port) { + selectedSlave = slave; + break; + } + } + } + if (selectedSlave) { + break; + } + } + } + // if none of the preferred slaves are available, a random available slave is returned + if (!selectedSlave) { + selectedSlave = utils_1.sample(availableSlaves); + } + return addressResponseToAddress(selectedSlave); } +function addressResponseToAddress(input) { + return { host: input.ip, port: Number(input.port) }; +} +function noop() { } -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; - - inspectNode(object, objects, duplicatesIndexes); - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); -} +/***/ }), -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; +/***/ 8774: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); +"use strict"; - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __nccwpck_require__(11631); +const tls_1 = __nccwpck_require__(4016); +const utils_1 = __nccwpck_require__(94832); +const AbstractConnector_1 = __nccwpck_require__(72712); +function isIIpcConnectionOptions(value) { + return value.path; +} +exports.isIIpcConnectionOptions = isIIpcConnectionOptions; +class StandaloneConnector extends AbstractConnector_1.default { + constructor(options) { + super(); + this.options = options; + } + connect(_) { + const { options } = this; + this.connecting = true; + let connectionOptions; + if (isIIpcConnectionOptions(options)) { + connectionOptions = { + path: options.path, + }; + } + else { + connectionOptions = {}; + if (options.port != null) { + connectionOptions.port = options.port; + } + if (options.host != null) { + connectionOptions.host = options.host; + } + if (options.family != null) { + connectionOptions.family = options.family; + } } - } else { - objectKeyList = Object.keys(object); - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + if (options.tls) { + Object.assign(connectionOptions, options.tls); } - } + // TODO: + // We use native Promise here since other Promise + // implementation may use different schedulers that + // cause issue when the stream is resolved in the + // next tick. + // Should use the provided promise in the next major + // version and do not connect before resolved. + return new Promise((resolve, reject) => { + process.nextTick(() => { + if (!this.connecting) { + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return; + } + try { + if (options.tls) { + this.stream = tls_1.connect(connectionOptions); + } + else { + this.stream = net_1.createConnection(connectionOptions); + } + } + catch (err) { + reject(err); + return; + } + resolve(this.stream); + }); + }); } - } } +exports.default = StandaloneConnector; -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; +/***/ }), - return ''; -} +/***/ 72340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function safeDump(input, options) { - return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} +"use strict"; -module.exports.dump = dump; -module.exports.safeDump = safeDump; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const StandaloneConnector_1 = __nccwpck_require__(8774); +exports.StandaloneConnector = StandaloneConnector_1.default; +const SentinelConnector_1 = __nccwpck_require__(10379); +exports.SentinelConnector = SentinelConnector_1.default; /***/ }), -/***/ 65199: -/***/ ((module) => { +/***/ 97282: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// - - -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +class ClusterAllFailedError extends redis_errors_1.RedisError { + constructor(message, lastNodeError) { + super(message); + this.lastNodeError = lastNodeError; + Error.captureStackTrace(this, this.constructor); + } + get name() { + return this.constructor.name; + } } - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { - var result = this.name + ': '; - - result += this.reason || '(unknown reason)'; - - if (!compact && this.mark) { - result += ' ' + this.mark.toString(); - } - - return result; -}; - - -module.exports = YAMLException; +exports.default = ClusterAllFailedError; /***/ }), -/***/ 45190: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 90735: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -/*eslint-disable max-len,no-use-before-define*/ - -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var Mark = __nccwpck_require__(55426); -var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); -var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); - - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - - -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; - - -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; - - -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - -function _class(obj) { return Object.prototype.toString.call(obj); } - -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} - -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} - -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} - -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +class MaxRetriesPerRequestError extends redis_errors_1.AbortError { + constructor(maxRetriesPerRequest) { + const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to "maxRetriesPerRequest" option for details.`; + super(message); + Error.captureStackTrace(this, this.constructor); + } + get name() { + return this.constructor.name; + } } +exports.default = MaxRetriesPerRequestError; -function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - /*eslint-disable no-bitwise*/ - lc = c | 0x20; +/***/ }), - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } +/***/ 23961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return -1; -} +"use strict"; -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); +exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - return -1; -} +/***/ }), -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} +/***/ 45069: +/***/ ((module, exports, __nccwpck_require__) => { -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} +"use strict"; -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports = module.exports = __nccwpck_require__(83609).default; +var redis_1 = __nccwpck_require__(83609); +exports.default = redis_1.default; +var cluster_1 = __nccwpck_require__(17208); +exports.Cluster = cluster_1.default; +var command_1 = __nccwpck_require__(90803); +exports.Command = command_1.default; +var ScanStream_1 = __nccwpck_require__(6134); +exports.ScanStream = ScanStream_1.default; +var pipeline_1 = __nccwpck_require__(42803); +exports.Pipeline = pipeline_1.default; +var AbstractConnector_1 = __nccwpck_require__(72712); +exports.AbstractConnector = AbstractConnector_1.default; +var SentinelConnector_1 = __nccwpck_require__(10379); +exports.SentinelConnector = SentinelConnector_1.default; +exports.SentinelIterator = SentinelConnector_1.SentinelIterator; +// No TS typings +exports.ReplyError = __nccwpck_require__(81879).ReplyError; +const PromiseContainer = __nccwpck_require__(71475); +Object.defineProperty(exports, "Promise", ({ + get() { + return PromiseContainer.get(); + }, + set(lib) { + PromiseContainer.set(lib); + }, +})); +function print(err, reply) { + if (err) { + console.log("Error: " + err); + } + else { + console.log("Reply: " + reply); + } } +exports.print = print; -function State(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.onWarning = options['onWarning'] || null; - this.legacy = options['legacy'] || false; - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - -} +/***/ }), +/***/ 42803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function generateError(state, message) { - return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); -} +"use strict"; -function throwError(state, message) { - throw generateError(state, message); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(90803); +const util_1 = __nccwpck_require__(31669); +const standard_as_callback_1 = __nccwpck_require__(91543); +const redis_commands_1 = __nccwpck_require__(98020); +const calculateSlot = __nccwpck_require__(48481); +const pMap = __nccwpck_require__(12071); +const PromiseContainer = __nccwpck_require__(71475); +const commander_1 = __nccwpck_require__(33642); +/* + This function derives from the cluster-key-slot implementation. + Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes. + If this is satisfied, it returns the first key's slot. +*/ +function generateMultiWithNodes(redis, keys) { + const slot = calculateSlot(keys[0]); + const target = redis.slots[slot].join(","); + for (let i = 1; i < keys.length; i++) { + const currentTarget = redis.slots[calculateSlot(keys[i])].join(","); + if (currentTarget !== target) { + return -1; + } + } + return slot; } - -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } +function Pipeline(redis) { + commander_1.default.call(this); + this.redis = redis; + this.isCluster = this.redis.constructor.name === "Cluster"; + this.isPipeline = true; + this.options = redis.options; + this._queue = []; + this._result = []; + this._transactions = 0; + this._shaToScript = {}; + Object.keys(redis.scriptsSet).forEach((name) => { + const script = redis.scriptsSet[name]; + this._shaToScript[script.sha] = script; + this[name] = redis[name]; + this[name + "Buffer"] = redis[name + "Buffer"]; + }); + const Promise = PromiseContainer.get(); + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + const _this = this; + Object.defineProperty(this, "length", { + get: function () { + return _this._queue.length; + }, + }); } - - -var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); +exports.default = Pipeline; +Object.assign(Pipeline.prototype, commander_1.default.prototype); +Pipeline.prototype.fillResult = function (value, position) { + if (this._queue[position].name === "exec" && Array.isArray(value[1])) { + const execLength = value[1].length; + for (let i = 0; i < execLength; i++) { + if (value[1][i] instanceof Error) { + continue; + } + const cmd = this._queue[position - (execLength - i)]; + try { + value[1][i] = cmd.transformReply(value[1][i]); + } + catch (err) { + value[1][i] = err; + } + } + } + this._result[position] = value; + if (--this.replyPending) { + return; + } + if (this.isCluster) { + let retriable = true; + let commonError; + for (let i = 0; i < this._result.length; ++i) { + const error = this._result[i][0]; + const command = this._queue[i]; + if (error) { + if (command.name === "exec" && + error.message === + "EXECABORT Transaction discarded because of previous errors.") { + continue; + } + if (!commonError) { + commonError = { + name: error.name, + message: error.message, + }; + } + else if (commonError.name !== error.name || + commonError.message !== error.message) { + retriable = false; + break; + } + } + else if (!command.inTransaction) { + const isReadOnly = redis_commands_1.exists(command.name) && redis_commands_1.hasFlag(command.name, "readonly"); + if (!isReadOnly) { + retriable = false; + break; + } + } + } + if (commonError && retriable) { + const _this = this; + const errv = commonError.message.split(" "); + const queue = this._queue; + let inTransaction = false; + this._queue = []; + for (let i = 0; i < queue.length; ++i) { + if (errv[0] === "ASK" && + !inTransaction && + queue[i].name !== "asking" && + (!queue[i - 1] || queue[i - 1].name !== "asking")) { + const asking = new command_1.default("asking"); + asking.ignore = true; + this.sendCommand(asking); + } + queue[i].initPromise(); + this.sendCommand(queue[i]); + inTransaction = queue[i].inTransaction; + } + let matched = true; + if (typeof this.leftRedirections === "undefined") { + this.leftRedirections = {}; + } + const exec = function () { + _this.exec(); + }; + this.redis.handleError(commonError, this.leftRedirections, { + moved: function (slot, key) { + _this.preferKey = key; + _this.redis.slots[errv[1]] = [key]; + _this.redis.refreshSlotsCache(); + _this.exec(); + }, + ask: function (slot, key) { + _this.preferKey = key; + _this.exec(); + }, + tryagain: exec, + clusterDown: exec, + connectionClosed: exec, + maxRedirections: () => { + matched = false; + }, + defaults: () => { + matched = false; + }, + }); + if (matched) { + return; + } + } } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); + let ignoredCount = 0; + for (let i = 0; i < this._queue.length - ignoredCount; ++i) { + if (this._queue[i + ignoredCount].ignore) { + ignoredCount += 1; + } + this._result[i] = this._result[i + ignoredCount]; } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); + this.resolve(this._result.slice(0, this._result.length - ignoredCount)); +}; +Pipeline.prototype.sendCommand = function (command) { + if (this._transactions > 0) { + command.inTransaction = true; } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); + const position = this._queue.length; + command.pipelineIndex = position; + command.promise + .then((result) => { + this.fillResult([null, result], position); + }) + .catch((error) => { + this.fillResult([error], position); + }); + this._queue.push(command); + return this; +}; +Pipeline.prototype.addBatch = function (commands) { + let command, commandName, args; + for (let i = 0; i < commands.length; ++i) { + command = commands[i]; + commandName = command[0]; + args = command.slice(1); + this[commandName].apply(this, args); } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); + return this; +}; +const multi = Pipeline.prototype.multi; +Pipeline.prototype.multi = function () { + this._transactions += 1; + return multi.apply(this, arguments); +}; +const execBuffer = Pipeline.prototype.execBuffer; +const exec = Pipeline.prototype.exec; +Pipeline.prototype.execBuffer = util_1.deprecate(function () { + if (this._transactions > 0) { + this._transactions -= 1; } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); + return execBuffer.apply(this, arguments); +}, "Pipeline#execBuffer: Use Pipeline#exec instead"); +Pipeline.prototype.exec = function (callback) { + // Wait for the cluster to be connected, since we need nodes information before continuing + if (this.isCluster && !this.redis.slots.length) { + this.redis.delayUntilReady((err) => { + if (err) { + callback(err); + return; + } + this.exec(callback); + }); + return this.promise; } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + if (this._transactions > 0) { + this._transactions -= 1; + return (this.options.dropBufferSupport ? exec : execBuffer).apply(this, arguments); } - - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + if (!this.nodeifiedPromise) { + this.nodeifiedPromise = true; + standard_as_callback_1.default(this.promise, callback); } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + if (!this._queue.length) { + this.resolve([]); } - - state.tagMap[handle] = prefix; - } -}; - - -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); + let pipelineSlot; + if (this.isCluster) { + // List of the first key for each command + const sampleKeys = []; + for (let i = 0; i < this._queue.length; i++) { + const keys = this._queue[i].getKeys(); + if (keys.length) { + sampleKeys.push(keys[0]); + } + // For each command, check that the keys belong to the same slot + if (keys.length && calculateSlot.generateMulti(keys) < 0) { + this.reject(new Error("All the keys in a pipeline command should belong to the same slot")); + return this.promise; + } + } + if (sampleKeys.length) { + pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys); + if (pipelineSlot < 0) { + this.reject(new Error("All keys in the pipeline should belong to the same slots allocation group")); + return this.promise; + } + } + else { + // Send the pipeline to a random node + pipelineSlot = (Math.random() * 16384) | 0; } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); } + // Check whether scripts exists + const scripts = []; + for (let i = 0; i < this._queue.length; ++i) { + const item = this._queue[i]; + if (item.name !== "evalsha") { + continue; + } + const script = this._shaToScript[item.args[0]]; + if (!script || this.redis._addedScriptHashes[script.sha]) { + continue; + } + scripts.push(script); + this.redis._addedScriptHashes[script.sha] = true; + } + const _this = this; + if (!scripts.length) { + return execPipeline(); + } + // In cluster mode, always load scripts before running the pipeline + if (this.isCluster) { + return pMap(scripts, (script) => _this.redis.script("load", script.lua), { + concurrency: 10, + }).then(execPipeline); + } + return this.redis + .script("exists", scripts.map(({ sha }) => sha)) + .then(function (results) { + const pending = []; + for (let i = 0; i < results.length; ++i) { + if (!results[i]) { + pending.push(scripts[i]); + } + } + const Promise = PromiseContainer.get(); + return Promise.all(pending.map(function (script) { + return _this.redis.script("load", script.lua); + })); + }) + .then(execPipeline); + function execPipeline() { + let data = ""; + let buffers; + let writePending = (_this.replyPending = _this._queue.length); + let node; + if (_this.isCluster) { + node = { + slot: pipelineSlot, + redis: _this.redis.connectionPool.nodes.all[_this.preferKey], + }; + } + let bufferMode = false; + const stream = { + write: function (writable) { + if (writable instanceof Buffer) { + bufferMode = true; + } + if (bufferMode) { + if (!buffers) { + buffers = []; + } + if (typeof data === "string") { + buffers.push(Buffer.from(data, "utf8")); + data = undefined; + } + buffers.push(typeof writable === "string" + ? Buffer.from(writable, "utf8") + : writable); + } + else { + data += writable; + } + if (!--writePending) { + let sendData; + if (buffers) { + sendData = Buffer.concat(buffers); + } + else { + sendData = data; + } + if (_this.isCluster) { + node.redis.stream.write(sendData); + } + else { + _this.redis.stream.write(sendData); + } + // Reset writePending for resending + writePending = _this._queue.length; + data = ""; + buffers = undefined; + bufferMode = false; + } + }, + }; + for (let i = 0; i < _this._queue.length; ++i) { + _this.redis.sendCommand(_this._queue[i], stream, node); + } + return _this.promise; + } +}; - state.result += _result; - } -} - -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } +/***/ }), - sourceKeys = Object.keys(source); +/***/ 71475: +/***/ ((__unused_webpack_module, exports) => { - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; +"use strict"; - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isPromise(obj) { + return (!!obj && + (typeof obj === "object" || typeof obj === "function") && + typeof obj.then === "function"); +} +exports.isPromise = isPromise; +let promise = Promise; +function get() { + return promise; +} +exports.get = get; +function set(lib) { + if (typeof lib !== "function") { + throw new Error(`Provided Promise must be a function, got ${lib}`); } - } + promise = lib; } +exports.set = set; -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { - var index, quantity; - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); +/***/ }), - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } +/***/ 1422: +/***/ ((__unused_webpack_module, exports) => { - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } +"use strict"; - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_REDIS_OPTIONS = { + // Connection + port: 6379, + host: "localhost", + family: 4, + connectTimeout: 10000, + retryStrategy: function (times) { + return Math.min(times * 50, 2000); + }, + keepAlive: 0, + noDelay: true, + connectionName: null, + // Sentinel + sentinels: null, + name: null, + role: "master", + sentinelRetryStrategy: function (times) { + return Math.min(times * 10, 1000); + }, + natMap: null, + enableTLSForSentinelMode: false, + updateSentinels: true, + // Status + username: null, + password: null, + db: 0, + // Others + dropBufferSupport: false, + enableOfflineQueue: true, + enableReadyCheck: true, + autoResubscribe: true, + autoResendUnfulfilledCommands: true, + lazyConnect: false, + keyPrefix: "", + reconnectOnError: null, + readOnly: false, + stringNumbers: false, + maxRetriesPerRequest: 20, + maxLoadingRetryTime: 10000, + enableAutoPipelining: false, + autoPipeliningIgnoredCommands: [], + maxScriptsCachingTime: 60000, +}; - keyNode = String(keyNode); +/***/ }), - if (_result === null) { - _result = {}; - } +/***/ 74276: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - _result[keyNode] = valueNode; - delete overridableKeys[keyNode]; - } +"use strict"; - return _result; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +const command_1 = __nccwpck_require__(90803); +const errors_1 = __nccwpck_require__(23961); +const utils_1 = __nccwpck_require__(94832); +const DataHandler_1 = __nccwpck_require__(30545); +const debug = utils_1.Debug("connection"); +function connectHandler(self) { + return function () { + self.setStatus("connect"); + self.resetCommandQueue(); + // AUTH command should be processed before any other commands + let flushed = false; + const { connectionEpoch } = self; + if (self.condition.auth) { + self.auth(self.condition.auth, function (err) { + if (connectionEpoch !== self.connectionEpoch) { + return; + } + if (err) { + if (err.message.indexOf("no password is set") !== -1) { + console.warn("[WARN] Redis server does not require a password, but a password was supplied."); + } + else if (err.message.indexOf("without any password configured for the default user") !== -1) { + console.warn("[WARN] This Redis server's `default` user does not require a password, but a password was supplied"); + } + else if (err.message.indexOf("wrong number of arguments for 'auth' command") !== -1) { + console.warn(`[ERROR] The server returned "wrong number of arguments for 'auth' command". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`); + } + else { + flushed = true; + self.recoverFromFatalError(err, err); + } + } + }); + } + if (self.condition.select) { + self.select(self.condition.select); + } + if (!self.options.enableReadyCheck) { + exports.readyHandler(self)(); + } + /* + No need to keep the reference of DataHandler here + because we don't need to do the cleanup. + `Stream#end()` will remove all listeners for us. + */ + new DataHandler_1.default(self, { + stringNumbers: self.options.stringNumbers, + dropBufferSupport: self.options.dropBufferSupport, + }); + if (self.options.enableReadyCheck) { + self._readyCheck(function (err, info) { + if (connectionEpoch !== self.connectionEpoch) { + return; + } + if (err) { + if (!flushed) { + self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err); + } + } + else { + self.serverInfo = info; + if (self.connector.check(info)) { + exports.readyHandler(self)(); + } + else { + self.disconnect(true); + } + } + }); + } + }; } - -function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; +exports.connectHandler = connectHandler; +function abortError(command) { + const err = new redis_errors_1.AbortError("Command aborted due to connection close"); + err.command = { + name: command.name, + args: command.args, + }; + return err; } - -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); +// If a contiguous set of pipeline commands starts from index zero then they +// can be safely reattempted. If however we have a chain of pipelined commands +// starting at index 1 or more it means we received a partial response before +// the connection close and those pipelined commands must be aborted. For +// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after +// aborting and purging we'll have a queue that looks like this: [0, 1, 2] +function abortIncompletePipelines(commandQueue) { + let expectedIndex = 0; + for (let i = 0; i < commandQueue.length;) { + const command = commandQueue.peekAt(i).command; + const pipelineIndex = command.pipelineIndex; + if (pipelineIndex === undefined || pipelineIndex === 0) { + expectedIndex = 0; + } + if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + continue; + } + i++; } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; +} +// If only a partial transaction result was received before connection close, +// we have to abort any transaction fragments that may have ended up in the +// offline queue +function abortTransactionFragments(commandQueue) { + for (let i = 0; i < commandQueue.length;) { + const command = commandQueue.peekAt(i).command; + if (command.name === "multi") { + break; + } + if (command.name === "exec") { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + break; + } + if (command.inTransaction) { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + } + else { + i++; + } } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; } - -function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; +function closeHandler(self) { + return function () { + self.setStatus("close"); + if (!self.prevCondition) { + self.prevCondition = self.condition; + } + if (self.commandQueue.length) { + abortIncompletePipelines(self.commandQueue); + self.prevCommandQueue = self.commandQueue; + } + if (self.offlineQueue.length) { + abortTransactionFragments(self.offlineQueue); + } + if (self.manuallyClosing) { + self.manuallyClosing = false; + debug("skip reconnecting since the connection is manually closed."); + return close(); + } + if (typeof self.options.retryStrategy !== "function") { + debug("skip reconnecting because `retryStrategy` is not a function"); + return close(); + } + const retryDelay = self.options.retryStrategy(++self.retryAttempts); + if (typeof retryDelay !== "number") { + debug("skip reconnecting because `retryStrategy` doesn't return a number"); + return close(); + } + debug("reconnect in %sms", retryDelay); + self.setStatus("reconnecting", retryDelay); + self.reconnectTimeout = setTimeout(function () { + self.reconnectTimeout = null; + self.connect().catch(utils_1.noop); + }, retryDelay); + const { maxRetriesPerRequest } = self.options; + if (typeof maxRetriesPerRequest === "number") { + if (maxRetriesPerRequest < 0) { + debug("maxRetriesPerRequest is negative, ignoring..."); + } + else { + const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); + if (remainder === 0) { + debug("reach maxRetriesPerRequest limitation, flushing command queue..."); + self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); + } + } + } + }; + function close() { + self.setStatus("end"); + self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); } - } - - return false; } - -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } +exports.closeHandler = closeHandler; +function errorHandler(self) { + return function (error) { + debug("error: %s", error); + self.silentEmit("error", error); + }; +} +exports.errorHandler = errorHandler; +function readyHandler(self) { + return function () { + self.setStatus("ready"); + self.retryAttempts = 0; + if (self.options.monitor) { + self.call("monitor"); + const { sendCommand } = self; + self.sendCommand = function (command) { + if (command_1.default.checkFlag("VALID_IN_MONITOR_MODE", command.name)) { + return sendCommand.call(self, command); + } + command.reject(new Error("Connection is in monitoring mode, can't process commands.")); + return command.promise; + }; + self.once("close", function () { + delete self.sendCommand; + }); + self.setStatus("monitoring"); + return; + } + const finalSelect = self.prevCondition + ? self.prevCondition.select + : self.condition.select; + if (self.options.connectionName) { + debug("set the connection name [%s]", self.options.connectionName); + self.client("setname", self.options.connectionName).catch(utils_1.noop); + } + if (self.options.readOnly) { + debug("set the connection to readonly mode"); + self.readonly().catch(utils_1.noop); + } + if (self.prevCondition) { + const condition = self.prevCondition; + self.prevCondition = null; + if (condition.subscriber && self.options.autoResubscribe) { + // We re-select the previous db first since + // `SELECT` command is not valid in sub mode. + if (self.condition.select !== finalSelect) { + debug("connect to db [%d]", finalSelect); + self.select(finalSelect); + } + const subscribeChannels = condition.subscriber.channels("subscribe"); + if (subscribeChannels.length) { + debug("subscribe %d channels", subscribeChannels.length); + self.subscribe(subscribeChannels); + } + const psubscribeChannels = condition.subscriber.channels("psubscribe"); + if (psubscribeChannels.length) { + debug("psubscribe %d channels", psubscribeChannels.length); + self.psubscribe(psubscribeChannels); + } + } + } + if (self.prevCommandQueue) { + if (self.options.autoResendUnfulfilledCommands) { + debug("resend %d unfulfilled commands", self.prevCommandQueue.length); + while (self.prevCommandQueue.length > 0) { + const item = self.prevCommandQueue.shift(); + if (item.select !== self.condition.select && + item.command.name !== "select") { + self.select(item.select); + } + self.sendCommand(item.command, item.stream); + } + } + else { + self.prevCommandQueue = null; + } + } + if (self.offlineQueue.length) { + debug("send %d commands in offline queue", self.offlineQueue.length); + const offlineQueue = self.offlineQueue; + self.resetOfflineQueue(); + while (offlineQueue.length > 0) { + const item = offlineQueue.shift(); + if (item.select !== self.condition.select && + item.command.name !== "select") { + self.select(item.select); + } + self.sendCommand(item.command, item.stream); + } + } + if (self.condition.select !== finalSelect) { + debug("connect to db [%d]", finalSelect); + self.select(finalSelect); + } + }; } +exports.readyHandler = readyHandler; -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; +/***/ }), - ch = state.input.charCodeAt(state.position); +/***/ 83609: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } +"use strict"; - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lodash_1 = __nccwpck_require__(20961); +const util_1 = __nccwpck_require__(31669); +const events_1 = __nccwpck_require__(28614); +const Deque = __nccwpck_require__(42342); +const command_1 = __nccwpck_require__(90803); +const commander_1 = __nccwpck_require__(33642); +const utils_1 = __nccwpck_require__(94832); +const standard_as_callback_1 = __nccwpck_require__(91543); +const eventHandler = __nccwpck_require__(74276); +const connectors_1 = __nccwpck_require__(72340); +const ScanStream_1 = __nccwpck_require__(6134); +const commands = __nccwpck_require__(98020); +const PromiseContainer = __nccwpck_require__(71475); +const transaction_1 = __nccwpck_require__(14645); +const RedisOptions_1 = __nccwpck_require__(1422); +const debug = utils_1.Debug("redis"); +/** + * Creates a Redis instance + * + * @constructor + * @param {(number|string|Object)} [port=6379] - Port of the Redis server, + * or a URL string(see the examples below), + * or the `options` object(see the third argument). + * @param {string|Object} [host=localhost] - Host of the Redis server, + * when the first argument is a URL string, + * this argument is an object represents the options. + * @param {Object} [options] - Other options. + * @param {number} [options.port=6379] - Port of the Redis server. + * @param {string} [options.host=localhost] - Host of the Redis server. + * @param {string} [options.family=4] - Version of IP stack. Defaults to 4. + * @param {string} [options.path=null] - Local domain socket path. If set the `port`, + * `host` and `family` will be ignored. + * @param {number} [options.keepAlive=0] - TCP KeepAlive on the socket with a X ms delay before start. + * Set to a non-number value to disable keepAlive. + * @param {boolean} [options.noDelay=true] - Whether to disable the Nagle's Algorithm. By default we disable + * it to reduce the latency. + * @param {string} [options.connectionName=null] - Connection name. + * @param {number} [options.db=0] - Database index to use. + * @param {string} [options.username=null] - If set, client will send AUTH command with this user and password when connected. + * @param {string} [options.password=null] - If set, client will send AUTH command + * with the value of this option when connected. + * @param {boolean} [options.dropBufferSupport=false] - Drop the buffer support for better performance. + * This option is recommended to be enabled when + * handling large array response and you don't need the buffer support. + * @param {boolean} [options.enableReadyCheck=true] - When a connection is established to + * the Redis server, the server might still be loading the database from disk. + * While loading, the server not respond to any commands. + * To work around this, when this option is `true`, + * ioredis will check the status of the Redis server, + * and when the Redis server is able to process commands, + * a `ready` event will be emitted. + * @param {boolean} [options.enableOfflineQueue=true] - By default, + * if there is no active connection to the Redis server, + * commands are added to a queue and are executed once the connection is "ready" + * (when `enableReadyCheck` is `true`, + * "ready" means the Redis server has loaded the database from disk, otherwise means the connection + * to the Redis server has been established). If this option is false, + * when execute the command when the connection isn't ready, an error will be returned. + * @param {number} [options.connectTimeout=10000] - The milliseconds before a timeout occurs during the initial + * connection to the Redis server. + * @param {boolean} [options.autoResubscribe=true] - After reconnected, if the previous connection was in the + * subscriber mode, client will auto re-subscribe these channels. + * @param {boolean} [options.autoResendUnfulfilledCommands=true] - If true, client will resend unfulfilled + * commands(e.g. block commands) in the previous connection when reconnected. + * @param {boolean} [options.lazyConnect=false] - By default, + * When a new `Redis` instance is created, it will connect to Redis server automatically. + * If you want to keep the instance disconnected until a command is called, you can pass the `lazyConnect` option to + * the constructor: + * + * ```javascript + * var redis = new Redis({ lazyConnect: true }); + * // No attempting to connect to the Redis server here. - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; + * // Now let's connect to the Redis server + * redis.get('foo', function () { + * }); + * ``` + * @param {Object} [options.tls] - TLS connection support. See https://github.com/luin/ioredis#tls-options + * @param {string} [options.keyPrefix=''] - The prefix to prepend to all keys in a command. + * @param {function} [options.retryStrategy] - See "Quick Start" section + * @param {number} [options.maxRetriesPerRequest] - See "Quick Start" section + * @param {number} [options.maxLoadingRetryTime=10000] - when redis server is not ready, we will wait for + * `loading_eta_seconds` from `info` command or maxLoadingRetryTime (milliseconds), whichever is smaller. + * @param {function} [options.reconnectOnError] - See "Quick Start" section + * @param {boolean} [options.readOnly=false] - Enable READONLY mode for the connection. + * Only available for cluster mode. + * @param {boolean} [options.stringNumbers=false] - Force numbers to be always returned as JavaScript + * strings. This option is necessary when dealing with big numbers (exceed the [-2^53, +2^53] range). + * @param {boolean} [options.enableTLSForSentinelMode=false] - Whether to support the `tls` option + * when connecting to Redis via sentinel mode. + * @param {NatMap} [options.natMap=null] NAT map for sentinel connector. + * @param {boolean} [options.updateSentinels=true] - Update the given `sentinels` list with new IP + * addresses when communicating with existing sentinels. +* @param {boolean} [options.enableAutoPipelining=false] - When enabled, all commands issued during an event loop + * iteration are automatically wrapped in a pipeline and sent to the server at the same time. + * This can dramatically improve performance. + * @param {string[]} [options.autoPipeliningIgnoredCommands=[]] - The list of commands which must not be automatically wrapped in pipelines. + * @param {number} [options.maxScriptsCachingTime=60000] Default script definition caching time. + * @extends [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) + * @extends Commander + * @example + * ```js + * var Redis = require('ioredis'); + * + * var redis = new Redis(); + * + * var redisOnPort6380 = new Redis(6380); + * var anotherRedis = new Redis(6380, '192.168.100.1'); + * var unixSocketRedis = new Redis({ path: '/tmp/echo.sock' }); + * var unixSocketRedis2 = new Redis('/tmp/echo.sock'); + * var urlRedis = new Redis('redis://user:password@redis-service.com:6379/'); + * var urlRedis2 = new Redis('//localhost:6379'); + * var urlRedisTls = new Redis('rediss://user:password@redis-service.com:6379/'); + * var authedRedis = new Redis(6380, '192.168.100.1', { password: 'password' }); + * ``` + */ +exports.default = Redis; +function Redis() { + if (!(this instanceof Redis)) { + console.error(new Error("Calling `Redis()` like a function is deprecated. Using `new Redis()` instead.").stack.replace("Error", "Warning")); + return new Redis(arguments[0], arguments[1], arguments[2]); } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } + this.parseOptions(arguments[0], arguments[1], arguments[2]); + events_1.EventEmitter.call(this); + commander_1.default.call(this); + this.resetCommandQueue(); + this.resetOfflineQueue(); + this.connectionEpoch = 0; + if (this.options.Connector) { + this.connector = new this.options.Connector(this.options); } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; + else if (this.options.sentinels) { + this.connector = new connectors_1.SentinelConnector(this.options); } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; + else { + this.connector = new connectors_1.StandaloneConnector(this.options); } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; -} - -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; + this.retryAttempts = 0; + // Prepare a cache of scripts and setup a interval which regularly clears it + this._addedScriptHashes = {}; + // Prepare autopipelines structures + this._autoPipelines = new Map(); + this._runningAutoPipelines = new Set(); + Object.defineProperty(this, "autoPipelineQueueSize", { + get() { + let queued = 0; + for (const pipeline of this._autoPipelines.values()) { + queued += pipeline.length; + } + return queued; + }, + }); + // end(or wait) -> connecting -> connect -> ready -> end + if (this.options.lazyConnect) { + this.setStatus("wait"); + } + else { + this.connect().catch(lodash_1.noop); } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); } - -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); - } +util_1.inherits(Redis, events_1.EventEmitter); +Object.assign(Redis.prototype, commander_1.default.prototype); +/** + * Create a Redis instance + * + * @deprecated + */ +// @ts-ignore +Redis.createClient = function (...args) { + // @ts-ignore + return new Redis(...args); +}; +/** + * Default options + * + * @var defaultOptions + * @private + */ +Redis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS; +Redis.prototype.resetCommandQueue = function () { + this.commandQueue = new Deque(); +}; +Redis.prototype.resetOfflineQueue = function () { + this.offlineQueue = new Deque(); +}; +Redis.prototype.parseOptions = function () { + this.options = {}; + let isTls = false; + for (let i = 0; i < arguments.length; ++i) { + const arg = arguments[i]; + if (arg === null || typeof arg === "undefined") { + continue; + } + if (typeof arg === "object") { + lodash_1.defaults(this.options, arg); + } + else if (typeof arg === "string") { + lodash_1.defaults(this.options, utils_1.parseURL(arg)); + if (arg.startsWith("rediss://")) { + isTls = true; + } + } + else if (typeof arg === "number") { + this.options.port = arg; + } + else { + throw new Error("Invalid argument " + arg); } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); - } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} - -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = {}, - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); + if (isTls) { + lodash_1.defaults(this.options, { tls: true }); } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } + lodash_1.defaults(this.options, Redis.defaultOptions); + if (typeof this.options.port === "string") { + this.options.port = parseInt(this.options.port, 10); } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; + if (typeof this.options.db === "string") { + this.options.db = parseInt(this.options.db, 10); } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); - } else { - _result.push(keyNode); + if (this.options.parser === "hiredis") { + console.warn("Hiredis parser is abandoned since ioredis v3.0, and JavaScript parser will be used"); } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; +}; +/** + * Change instance's status + * @private + */ +Redis.prototype.setStatus = function (status, arg) { + // @ts-ignore + if (debug.enabled) { + debug("status[%s]: %s -> %s", this._getDescription(), this.status || "[empty]", status); } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); -} - -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; + this.status = status; + process.nextTick(this.emit.bind(this, status, arg)); +}; +/** + * Create a connection to Redis. + * This method will be invoked automatically when creating a new Redis instance + * unless `lazyConnect: true` is passed. + * + * When calling this method manually, a Promise is returned, which will + * be resolved when the connection status is ready. + * @param {function} [callback] + * @return {Promise} + * @public + */ +Redis.prototype.connect = function (callback) { + const _Promise = PromiseContainer.get(); + const promise = new _Promise((resolve, reject) => { + if (this.status === "connecting" || + this.status === "connect" || + this.status === "ready") { + reject(new Error("Redis is already connecting/connected")); + return; + } + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = setInterval(() => { + this._addedScriptHashes = {}; + }, this.options.maxScriptsCachingTime); + this.connectionEpoch += 1; + this.setStatus("connecting"); + const { options } = this; + this.condition = { + select: options.db, + auth: options.username + ? [options.username, options.password] + : options.password, + subscriber: false, + }; + const _this = this; + standard_as_callback_1.default(this.connector.connect(function (type, err) { + _this.silentEmit(type, err); + }), function (err, stream) { + if (err) { + _this.flushQueue(err); + _this.silentEmit("error", err); + reject(err); + _this.setStatus("end"); + return; + } + let CONNECT_EVENT = options.tls ? "secureConnect" : "connect"; + if (options.sentinels && !options.enableTLSForSentinelMode) { + CONNECT_EVENT = "connect"; + } + _this.stream = stream; + if (typeof options.keepAlive === "number") { + stream.setKeepAlive(true, options.keepAlive); + } + if (stream.connecting) { + stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); + if (options.connectTimeout) { + /* + * Typically, Socket#setTimeout(0) will clear the timer + * set before. However, in some platforms (Electron 3.x~4.x), + * the timer will not be cleared. So we introduce a variable here. + * + * See https://github.com/electron/electron/issues/14915 + */ + let connectTimeoutCleared = false; + stream.setTimeout(options.connectTimeout, function () { + if (connectTimeoutCleared) { + return; + } + stream.setTimeout(0); + stream.destroy(); + const err = new Error("connect ETIMEDOUT"); + // @ts-ignore + err.errorno = "ETIMEDOUT"; + // @ts-ignore + err.code = "ETIMEDOUT"; + // @ts-ignore + err.syscall = "connect"; + eventHandler.errorHandler(_this)(err); + }); + stream.once(CONNECT_EVENT, function () { + connectTimeoutCleared = true; + stream.setTimeout(0); + }); + } + } + else { + process.nextTick(eventHandler.connectHandler(_this)); + } + stream.once("error", eventHandler.errorHandler(_this)); + stream.once("close", eventHandler.closeHandler(_this)); + if (options.noDelay) { + stream.setNoDelay(true); + } + const connectionReadyHandler = function () { + _this.removeListener("close", connectionCloseHandler); + resolve(); + }; + var connectionCloseHandler = function () { + _this.removeListener("ready", connectionReadyHandler); + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + }; + _this.once("ready", connectionReadyHandler); + _this.once("close", connectionCloseHandler); + }); + }); + return standard_as_callback_1.default(promise, callback); +}; +/** + * Disconnect from Redis. + * + * This method closes the connection immediately, + * and may lose some pending replies that haven't written to client. + * If you want to wait for the pending replies, use Redis#quit instead. + * @public + */ +Redis.prototype.disconnect = function (reconnect) { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + if (!reconnect) { + this.manuallyClosing = true; } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); + if (this.reconnectTimeout && !reconnect) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); + if (this.status === "wait") { + eventHandler.closeHandler(this)(); } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; + else { + this.connector.disconnect(); + } +}; +/** + * Disconnect from Redis. + * + * @deprecated + */ +Redis.prototype.end = function () { + this.disconnect(); +}; +/** + * Create a new instance with the same options as the current one. + * + * @example + * ```js + * var redis = new Redis(6380); + * var anotherRedis = redis.duplicate(); + * ``` + * + * @public + */ +Redis.prototype.duplicate = function (override) { + return new Redis(Object.assign({}, this.options, override || {})); +}; +Redis.prototype.recoverFromFatalError = function (commandError, err, options) { + this.flushQueue(err, options); + this.silentEmit("error", err); + this.disconnect(true); +}; +Redis.prototype.handleReconnection = function handleReconnection(err, item) { + let needReconnect = false; + if (this.options.reconnectOnError) { + needReconnect = this.options.reconnectOnError(err); + } + switch (needReconnect) { + case 1: + case true: + if (this.status !== "reconnecting") { + this.disconnect(true); + } + item.command.reject(err); + break; + case 2: + if (this.status !== "reconnecting") { + this.disconnect(true); + } + if (this.condition.select !== item.select && + item.command.name !== "select") { + this.select(item.select); + } + this.sendCommand(item.command); + break; + default: + item.command.reject(err); } - - if (is_EOL(ch)) { - emptyLines++; - continue; +}; +/** + * Flush offline queue and command queue with error. + * + * @param {Error} error - The error object to send to the commands + * @param {object} options + * @private + */ +Redis.prototype.flushQueue = function (error, options) { + options = lodash_1.defaults({}, options, { + offlineQueue: true, + commandQueue: true, + }); + let item; + if (options.offlineQueue) { + while (this.offlineQueue.length > 0) { + item = this.offlineQueue.shift(); + item.command.reject(error); + } } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; + if (options.commandQueue) { + if (this.commandQueue.length > 0) { + if (this.stream) { + this.stream.removeAllListeners("data"); + } + while (this.commandQueue.length > 0) { + item = this.commandQueue.shift(); + item.command.reject(error); + } } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; +}; +/** + * Check whether Redis has finished loading the persistent data and is able to + * process commands. + * + * @param {Function} callback + * @private + */ +Redis.prototype._readyCheck = function (callback) { + const _this = this; + this.info(function (err, res) { + if (err) { + return callback(err); + } + if (typeof res !== "string") { + return callback(null, res); + } + const info = {}; + const lines = res.split("\r\n"); + for (let i = 0; i < lines.length; ++i) { + const [fieldName, ...fieldValueParts] = lines[i].split(":"); + const fieldValue = fieldValueParts.join(":"); + if (fieldValue) { + info[fieldName] = fieldValue; + } + } + if (!info.loading || info.loading === "0") { + callback(null, info); + } + else { + const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000; + const retryTime = _this.options.maxLoadingRetryTime && + _this.options.maxLoadingRetryTime < loadingEtaMs + ? _this.options.maxLoadingRetryTime + : loadingEtaMs; + debug("Redis server still loading, trying again in " + retryTime + "ms"); + setTimeout(function () { + _this._readyCheck(callback); + }, retryTime); + } + }); +}; +/** + * Emit only when there's at least one listener. + * + * @param {string} eventName - Event to emit + * @param {...*} arguments - Arguments + * @return {boolean} Returns true if event had listeners, false otherwise. + * @private + */ +Redis.prototype.silentEmit = function (eventName) { + let error; + if (eventName === "error") { + error = arguments[1]; + if (this.status === "end") { + return; + } + if (this.manuallyClosing) { + // ignore connection related errors when manually disconnecting + if (error instanceof Error && + (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG || + // @ts-ignore + error.syscall === "connect" || + // @ts-ignore + error.syscall === "read")) { + return; + } } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); + if (this.listeners(eventName).length > 0) { + return this.emit.apply(this, arguments); } - - captureSegment(state, captureStart, state.position, false); - } - - return true; -} - -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - - if (ch !== 0x2D/* - */) { - break; + if (error && error instanceof Error) { + console.error("[ioredis] Unhandled error event:", error.stack); } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; + return false; +}; +/** + * Listen for all requests received by the server in real time. + * + * This command will create a new connection to Redis and send a + * MONITOR command via the new connection in order to avoid disturbing + * the current connection. + * + * @param {function} [callback] The callback function. If omit, a promise will be returned. + * @example + * ```js + * var redis = new Redis(); + * redis.monitor(function (err, monitor) { + * // Entering monitoring mode. + * monitor.on('monitor', function (time, args, source, database) { + * console.log(time + ": " + util.inspect(args)); + * }); + * }); + * + * // supports promise as well as other commands + * redis.monitor().then(function (monitor) { + * monitor.on('monitor', function (time, args, source, database) { + * console.log(time + ": " + util.inspect(args)); + * }); + * }); + * ``` + * @public + */ +Redis.prototype.monitor = function (callback) { + const monitorInstance = this.duplicate({ + monitor: true, + lazyConnect: false, + }); + const Promise = PromiseContainer.get(); + return standard_as_callback_1.default(new Promise(function (resolve) { + monitorInstance.once("monitoring", function () { + resolve(monitorInstance); + }); + }), callback); +}; +transaction_1.addTransactionSupport(Redis.prototype); +/** + * Send a command to Redis + * + * This method is used internally by the `Redis#set`, `Redis#lpush` etc. + * Most of the time you won't invoke this method directly. + * However when you want to send a command that is not supported by ioredis yet, + * this command will be useful. + * + * @method sendCommand + * @memberOf Redis# + * @param {Command} command - The Command instance to send. + * @see {@link Command} + * @example + * ```js + * var redis = new Redis(); + * + * // Use callback + * var get = new Command('get', ['foo'], 'utf8', function (err, result) { + * console.log(result); + * }); + * redis.sendCommand(get); + * + * // Use promise + * var set = new Command('set', ['foo', 'bar'], 'utf8'); + * set.promise.then(function (result) { + * console.log(result); + * }); + * redis.sendCommand(set); + * ``` + * @private + */ +Redis.prototype.sendCommand = function (command, stream) { + if (this.status === "wait") { + this.connect().catch(lodash_1.noop); } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } + if (this.status === "end") { + command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return command.promise; } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; + if (this.condition.subscriber && + !command_1.default.checkFlag("VALID_IN_SUBSCRIBER_MODE", command.name)) { + command.reject(new Error("Connection in subscriber mode, only subscriber commands may be used")); + return command.promise; } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; -} - -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _pos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = {}, - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - _pos = state.position; - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else { - break; // Reading is done. Go to the epilogue. + if (command.name === "quit") { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); + let writable = this.status === "ready" || + (!stream && + this.status === "connect" && + commands.exists(command.name) && + commands.hasFlag(command.name, "loading")); + if (!this.stream) { + writable = false; } - - if (state.lineIndent > nodeIndent && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; + else if (!this.stream.writable) { + writable = false; } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; -} - -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); + else if (this.stream._writableState && this.stream._writableState.ended) { + // https://github.com/iojs/io.js/pull/1217 + writable = false; } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); + if (!writable && !this.options.enableOfflineQueue) { + command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); + return command.promise; + } + if (!writable && command.name === "quit" && this.offlineQueue.length === 0) { + this.disconnect(); + command.resolve(Buffer.from("OK")); + return command.promise; + } + if (writable) { + // @ts-ignore + if (debug.enabled) { + debug("write command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); + } + (stream || this.stream).write(command.toWritable()); + this.commandQueue.push({ + command: command, + stream: stream, + select: this.condition.select, + }); + if (command_1.default.checkFlag("WILL_DISCONNECT", command.name)) { + this.manuallyClosing = true; } - } - - ch = state.input.charCodeAt(++state.position); } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); + else if (this.options.enableOfflineQueue) { + // @ts-ignore + if (debug.enabled) { + debug("queue command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); + } + this.offlineQueue.push({ + command: command, + stream: stream, + select: this.condition.select, + }); } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; -} - -function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; -} - -function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} - -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this { - if (allowToSeek) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; +"use strict"; - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const crypto_1 = __nccwpck_require__(76417); +const promiseContainer_1 = __nccwpck_require__(71475); +const command_1 = __nccwpck_require__(90803); +const standard_as_callback_1 = __nccwpck_require__(91543); +class Script { + constructor(lua, numberOfKeys = null, keyPrefix = "", readOnly = false) { + this.lua = lua; + this.numberOfKeys = numberOfKeys; + this.keyPrefix = keyPrefix; + this.readOnly = readOnly; + this.sha = crypto_1.createHash("sha1").update(lua).digest("hex"); } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; + execute(container, args, options, callback) { + if (typeof this.numberOfKeys === "number") { + args.unshift(this.numberOfKeys); } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; + if (this.keyPrefix) { + options.keyPrefix = this.keyPrefix; + } + if (this.readOnly) { + options.readOnly = true; + } + const evalsha = new command_1.default("evalsha", [this.sha].concat(args), options); + evalsha.isCustomCommand = true; + const result = container.sendCommand(evalsha); + if (promiseContainer_1.isPromise(result)) { + return standard_as_callback_1.default(result.catch((err) => { + if (err.toString().indexOf("NOSCRIPT") === -1) { + throw err; + } + return container.sendCommand(new command_1.default("eval", [this.lua].concat(args), options)); + }), callback); + } + // result is not a Promise--probably returned from a pipeline chain; however, + // we still need the callback to fire when the script is evaluated + standard_as_callback_1.default(evalsha.promise, callback); + return result; } +} +exports.default = Script; - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - } else if (readAlias(state)) { - hasContent = true; +/***/ }), - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } +/***/ 14645: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; +"use strict"; - if (state.tag === null) { - state.tag = '?'; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const standard_as_callback_1 = __nccwpck_require__(91543); +const pipeline_1 = __nccwpck_require__(42803); +function addTransactionSupport(redis) { + redis.pipeline = function (commands) { + const pipeline = new pipeline_1.default(this); + if (Array.isArray(commands)) { + pipeline.addBatch(commands); } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; + return pipeline; + }; + const { multi } = redis; + redis.multi = function (commands, options) { + if (typeof options === "undefined" && !Array.isArray(commands)) { + options = commands; + commands = null; } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } + if (options && options.pipeline === false) { + return multi.call(this); + } + const pipeline = new pipeline_1.default(this); + pipeline.multi(); + if (Array.isArray(commands)) { + pipeline.addBatch(commands); + } + const exec = pipeline.exec; + pipeline.exec = function (callback) { + // Wait for the cluster to be connected, since we need nodes information before continuing + if (this.isCluster && !this.redis.slots.length) { + return standard_as_callback_1.default(new Promise((resolve, reject) => { + this.redis.delayUntilReady((err) => { + if (err) { + reject(err); + return; + } + this.exec(pipeline).then(resolve, reject); + }); + }), callback); + } + if (this._transactions > 0) { + exec.call(pipeline); + } + // Returns directly when the pipeline + // has been called multiple times (retries). + if (this.nodeifiedPromise) { + return exec.call(pipeline); + } + const promise = exec.call(pipeline); + return standard_as_callback_1.default(promise.then(function (result) { + const execResult = result[result.length - 1]; + if (typeof execResult === "undefined") { + throw new Error("Pipeline cannot be used to send any commands when the `exec()` has been called on it."); + } + if (execResult[0]) { + execResult[0].previousErrors = []; + for (let i = 0; i < result.length - 1; ++i) { + if (result[i][0]) { + execResult[0].previousErrors.push(result[i][0]); + } + } + throw execResult[0]; + } + return utils_1.wrapMultiResult(execResult[1]); + }), callback); + }; + const { execBuffer } = pipeline; + pipeline.execBuffer = function (callback) { + if (this._transactions > 0) { + execBuffer.call(pipeline); + } + return pipeline.exec(callback); + }; + return pipeline; + }; + const { exec } = redis; + redis.exec = function (callback) { + return standard_as_callback_1.default(exec.call(this).then(function (results) { + if (Array.isArray(results)) { + results = utils_1.wrapMultiResult(results); + } + return results; + }), callback); + }; +} +exports.addTransactionSupport = addTransactionSupport; - if (state.tag !== null && state.tag !== '!') { - if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; +/***/ }), - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; +/***/ 85356: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } +"use strict"; - if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __nccwpck_require__(38237); +const MAX_ARGUMENT_LENGTH = 200; +exports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH; +const NAMESPACE_PREFIX = "ioredis"; +/** + * helper function that tried to get a string value for + * arbitrary "debug" arg + */ +function getStringValue(v) { + if (v === null) { + return; + } + switch (typeof v) { + case "boolean": + return; + case "number": + return; + case "object": + if (Buffer.isBuffer(v)) { + return v.toString("hex"); + } + if (Array.isArray(v)) { + return v.join(","); + } + try { + return JSON.stringify(v); + } + catch (e) { + return; + } + case "string": + return v; + } +} +exports.getStringValue = getStringValue; +/** + * helper function that redacts a string representation of a "debug" arg + */ +function genRedactedString(str, maxLen) { + const { length } = str; + return length <= maxLen + ? str + : str.slice(0, maxLen) + ' ... '; +} +exports.genRedactedString = genRedactedString; +/** + * a wrapper for the `debug` module, used to generate + * "debug functions" that trim the values in their output + */ +function genDebugFunction(namespace) { + const fn = debug_1.default(`${NAMESPACE_PREFIX}:${namespace}`); + function wrappedDebug(...args) { + if (!fn.enabled) { + return; // no-op + } + // we skip the first arg because that is the message + for (let i = 1; i < args.length; i++) { + const str = getStringValue(args[i]); + if (typeof str === "string" && str.length > MAX_ARGUMENT_LENGTH) { + args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH); + } } - } - } else { - throwError(state, 'unknown tag !<' + state.tag + '>'); + return fn.apply(null, args); } - } - - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; + Object.defineProperties(wrappedDebug, { + namespace: { + get() { + return fn.namespace; + }, + }, + enabled: { + get() { + return fn.enabled; + }, + }, + destroy: { + get() { + return fn.destroy; + }, + }, + log: { + get() { + return fn.log; + }, + set(l) { + fn.log = l; + }, + }, + }); + return wrappedDebug; } +exports.default = genDebugFunction; -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = {}; - state.anchorMap = {}; +/***/ }), - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); +/***/ 94832: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ch = state.input.charCodeAt(state.position); +"use strict"; - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url_1 = __nccwpck_require__(78835); +const lodash_1 = __nccwpck_require__(20961); +exports.defaults = lodash_1.defaults; +exports.noop = lodash_1.noop; +exports.flatten = lodash_1.flatten; +const debug_1 = __nccwpck_require__(85356); +exports.Debug = debug_1.default; +/** + * Test if two buffers are equal + * + * @export + * @param {Buffer} a + * @param {Buffer} b + * @returns {boolean} Whether the two buffers are equal + */ +function bufferEqual(a, b) { + if (typeof a.equals === "function") { + return a.equals(b); } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); + if (a.length !== b.length) { + return false; } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; + } } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); + return true; +} +exports.bufferEqual = bufferEqual; +/** + * Convert a buffer to string, supports buffer array + * + * @param {*} value - The input value + * @param {string} encoding - string encoding + * @return {*} The result + * @example + * ```js + * var input = [Buffer.from('foo'), [Buffer.from('bar')]] + * var res = convertBufferToString(input, 'utf8') + * expect(res).to.eql(['foo', ['bar']]) + * ``` + * @private + */ +function convertBufferToString(value, encoding) { + if (value instanceof Buffer) { + return value.toString(encoding); } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); + if (Array.isArray(value)) { + const length = value.length; + const res = Array(length); + for (let i = 0; i < length; ++i) { + res[i] = + value[i] instanceof Buffer && encoding === "utf8" + ? value[i].toString() + : convertBufferToString(value[i], encoding); + } + return res; } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); + return value; +} +exports.convertBufferToString = convertBufferToString; +/** + * Convert a list of results to node-style + * + * @param {Array} arr - The input value + * @return {Array} The output value + * @example + * ```js + * var input = ['a', 'b', new Error('c'), 'd'] + * var output = exports.wrapMultiResult(input) + * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) + * ``` + * @private + */ +function wrapMultiResult(arr) { + // When using WATCH/EXEC transactions, the EXEC will return + // a null instead of an array + if (!arr) { + return null; } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } + const result = []; + const length = arr.length; + for (let i = 0; i < length; ++i) { + const item = arr[i]; + if (item instanceof Error) { + result.push([item]); + } + else { + result.push([null, item]); + } + } + return result; } - - -function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; +exports.wrapMultiResult = wrapMultiResult; +/** + * Detect the argument is a int + * + * @param {string} value + * @return {boolean} Whether the value is a int + * @example + * ```js + * > isInt('123') + * true + * > isInt('123.3') + * false + * > isInt('1x') + * false + * > isInt(123) + * true + * > isInt(true) + * false + * ``` + * @private + */ +function isInt(value) { + const x = parseFloat(value); + return !isNaN(value) && (x | 0) === x; +} +exports.isInt = isInt; +/** + * Pack an array to an Object + * + * @param {array} array + * @return {object} + * @example + * ```js + * > packObject(['a', 'b', 'c', 'd']) + * { a: 'b', c: 'd' } + * ``` + */ +function packObject(array) { + const result = {}; + const length = array.length; + for (let i = 1; i < length; i += 2) { + result[array[i - 1]] = array[i]; } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); + return result; +} +exports.packObject = packObject; +/** + * Return a callback with timeout + * + * @param {function} callback + * @param {number} timeout + * @return {function} + */ +function timeout(callback, timeout) { + let timer; + const run = function () { + if (timer) { + clearTimeout(timer); + timer = null; + callback.apply(this, arguments); + } + }; + timer = setTimeout(run, timeout, new Error("timeout")); + return run; +} +exports.timeout = timeout; +/** + * Convert an object to an array + * + * @param {object} obj + * @return {array} + * @example + * ```js + * > convertObjectToArray({ a: '1' }) + * ['a', '1'] + * ``` + */ +function convertObjectToArray(obj) { + const result = []; + const keys = Object.keys(obj); + for (let i = 0, l = keys.length; i < l; i++) { + result.push(keys[i], obj[keys[i]]); } - } - - var state = new State(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; + return result; } - - -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } +exports.convertObjectToArray = convertObjectToArray; +/** + * Convert a map to an array + * + * @param {Map} map + * @return {array} + * @example + * ```js + * > convertObjectToArray(new Map([[1, '2']])) + * [1, '2'] + * ``` + */ +function convertMapToArray(map) { + const result = []; + let pos = 0; + map.forEach(function (value, key) { + result[pos] = key; + result[pos + 1] = value; + pos += 2; + }); + return result; } - - -function load(input, options) { - var documents = loadDocuments(input, options); - - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); +exports.convertMapToArray = convertMapToArray; +/** + * Convert a non-string arg to a string + * + * @param {*} arg + * @return {string} + */ +function toArg(arg) { + if (arg === null || typeof arg === "undefined") { + return ""; + } + return String(arg); +} +exports.toArg = toArg; +/** + * Optimize error stack + * + * @param {Error} error - actually error + * @param {string} friendlyStack - the stack that more meaningful + * @param {string} filterPath - only show stacks with the specified path + */ +function optimizeErrorStack(error, friendlyStack, filterPath) { + const stacks = friendlyStack.split("\n"); + let lines = ""; + let i; + for (i = 1; i < stacks.length; ++i) { + if (stacks[i].indexOf(filterPath) === -1) { + break; + } + } + for (let j = i; j < stacks.length; ++j) { + lines += "\n" + stacks[j]; + } + const pos = error.stack.indexOf("\n"); + error.stack = error.stack.slice(0, pos) + lines; + return error; +} +exports.optimizeErrorStack = optimizeErrorStack; +/** + * Parse the redis protocol url + * + * @param {string} url - the redis protocol url + * @return {Object} + */ +function parseURL(url) { + if (isInt(url)) { + return { port: url }; + } + let parsed = url_1.parse(url, true, true); + if (!parsed.slashes && url[0] !== "/") { + url = "//" + url; + parsed = url_1.parse(url, true, true); + } + const result = {}; + if (parsed.auth) { + const parsedAuth = parsed.auth.split(":"); + result.password = parsedAuth[1]; + } + if (parsed.pathname) { + if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { + if (parsed.pathname.length > 1) { + result.db = parsed.pathname.slice(1); + } + } + else { + result.path = parsed.pathname; + } + } + if (parsed.host) { + result.host = parsed.hostname; + } + if (parsed.port) { + result.port = parsed.port; + } + lodash_1.defaults(result, parsed.query); + return result; +} +exports.parseURL = parseURL; +/** + * Get a random element from `array` + * + * @export + * @template T + * @param {T[]} array the array + * @param {number} [from=0] start index + * @returns {T} + */ +function sample(array, from = 0) { + const length = array.length; + if (from >= length) { + return; + } + return array[from + Math.floor(Math.random() * (length - from))]; +} +exports.sample = sample; +/** + * Shuffle the array using the Fisher-Yates Shuffle. + * This method will mutate the original array. + * + * @export + * @template T + * @param {T[]} array + * @returns {T[]} + */ +function shuffle(array) { + let counter = array.length; + // While there are elements in the array + while (counter > 0) { + // Pick a random index + const index = Math.floor(Math.random() * counter); + // Decrease counter by 1 + counter--; + // And swap the last element with it + [array[counter], array[index]] = [array[index], array[counter]]; + } + return array; } - - -function safeLoadAll(input, iterator, options) { - if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +exports.shuffle = shuffle; +/** + * Error message for connection being disconnected + */ +exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; +function zipMap(keys, values) { + const map = new Map(); + keys.forEach((key, index) => { + map.set(key, values[index]); + }); + return map; } +exports.zipMap = zipMap; -function safeLoad(input, options) { - return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} +/***/ }), +/***/ 20961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const defaults = __nccwpck_require__(11289); +exports.defaults = defaults; +const flatten = __nccwpck_require__(48919); +exports.flatten = flatten; +function noop() { } +exports.noop = noop; /***/ }), -/***/ 55426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 12071: +/***/ ((module) => { "use strict"; +const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { + options = Object.assign({ + concurrency: Infinity + }, options); -var common = __nccwpck_require__(59136); + if (typeof mapper !== 'function') { + throw new TypeError('Mapper function is required'); + } + const {concurrency} = options; -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; -} + if (!(typeof concurrency === 'number' && concurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); + } + const ret = []; + const iterator = iterable[Symbol.iterator](); + let isRejected = false; + let isIterableDone = false; + let resolvingCount = 0; + let currentIndex = 0; -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; + const next = () => { + if (isRejected) { + return; + } - if (!this.buffer) return null; + const nextItem = iterator.next(); + const i = currentIndex; + currentIndex++; - indent = indent || 4; - maxLength = maxLength || 75; + if (nextItem.done) { + isIterableDone = true; - head = ''; - start = this.position; + if (resolvingCount === 0) { + resolve(ret); + } - while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } - } + return; + } - tail = ''; - end = this.position; + resolvingCount++; - while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; - } - } + Promise.resolve(nextItem.value) + .then(element => mapper(element, i)) + .then( + value => { + ret[i] = value; + resolvingCount--; + next(); + }, + error => { + isRejected = true; + reject(error); + } + ); + }; - snippet = this.buffer.slice(start, end); + for (let i = 0; i < concurrency; i++) { + next(); - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; + if (isIterableDone) { + break; + } + } +}); +module.exports = pMap; +// TODO: Remove this for the next major release +module.exports.default = pMap; -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; - if (this.name) { - where += 'in "' + this.name + '" '; - } +/***/ }), - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); +/***/ 37263: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - if (!compact) { - snippet = this.getSnippet(); +/* module decorator */ module = __nccwpck_require__.nmd(module); +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; - if (snippet) { - where += ':\n' + snippet; - } - } + ipaddr = {}; - return where; -}; + root = this; + if (( true && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } -module.exports = Mark; + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; -/***/ }), + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } -/***/ 66514: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + IPv4.prototype.kind = function() { + return 'ipv4'; + }; -"use strict"; + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; -/*eslint-disable max-len*/ + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var Type = __nccwpck_require__(30967); + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; -function compileList(schema, name, result) { - var exclude = []; + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); - }); + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; - schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { - exclude.push(previousIndex); + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } } - }); - - result.push(currentType); - }); - - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); -} - + return 32 - cidr; + }; -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {} - }, index, length; + return IPv4; - function collectType(type) { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } + })(); - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; -} + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; -function Schema(definition) { - this.include = definition.include || []; - this.implicit = definition.implicit || []; - this.explicit = definition.explicit || []; + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; - this.implicit.forEach(function (type) { - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } } - }); - this.compiledImplicit = compileList(this, 'implicit', []); - this.compiledExplicit = compileList(this, 'explicit', []); - this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); -} + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; -Schema.DEFAULT = null; + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; -Schema.create = function createSchema() { - var schemas, types; + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; - switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); - } + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; - schemas = common.toArray(schemas); - types = common.toArray(types); + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - if (!schemas.every(function (schema) { return schema instanceof Schema; })) { - throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); - } + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; - if (!types.every(function (type) { return type instanceof Type; })) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; - return new Schema({ - include: schemas, - explicit: types - }); -}; + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + return IPv6; -module.exports = Schema; + })(); + ipv6Part = "(?:[0-9a-f]+::?)+"; -/***/ }), + zoneIndex = "%[0-9a-z]{1,}"; -/***/ 92183: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; -"use strict"; -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; -var Schema = __nccwpck_require__(66514); + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; -module.exports = new Schema({ - include: [ - __nccwpck_require__(1571) - ] -}); + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; -/***/ }), + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; -/***/ 56874: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; -"use strict"; -// JS-YAML's default schema for `load` function. -// It is not described in the YAML specification. -// -// This schema is based on JS-YAML's default safe schema and includes -// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. -// -// Also this schema is used as default base schema at `Schema.create` function. + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; -var Schema = __nccwpck_require__(66514); + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; -module.exports = Schema.DEFAULT = new Schema({ - include: [ - __nccwpck_require__(48949) - ], - explicit: [ - __nccwpck_require__(25914), - __nccwpck_require__(69242), - __nccwpck_require__(27278) - ] -}); +}).call(this); /***/ }), -/***/ 48949: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7604: +/***/ ((module) => { "use strict"; -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) - - +module.exports = function isArrayish(obj) { + if (!obj) { + return false; + } -var Schema = __nccwpck_require__(66514); - - -module.exports = new Schema({ - include: [ - __nccwpck_require__(92183) - ], - implicit: [ - __nccwpck_require__(83714), - __nccwpck_require__(81393) - ], - explicit: [ - __nccwpck_require__(32551), - __nccwpck_require__(96668), - __nccwpck_require__(76039), - __nccwpck_require__(69237) - ] -}); + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; /***/ }), -/***/ 66037: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 31310: +/***/ (function(module, exports) { -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 +;(function(root) { + 'use strict'; + function isBase64(v, opts) { + if (v instanceof Boolean || typeof v === 'boolean') { + return false + } + if (!(opts instanceof Object)) { + opts = {} + } + if (opts.allowEmpty === false && v === '') { + return false + } + var regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\/]{3}=)?' + var mimeRegex = '(data:\\w+\\/[a-zA-Z\\+\\-\\.]+;base64,)' -var Schema = __nccwpck_require__(66514); + if (opts.mimeRequired === true) { + regex = mimeRegex + regex + } else if (opts.allowMime === true) { + regex = mimeRegex + '?' + regex + } + if (opts.paddingRequired === false) { + regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' + } -module.exports = new Schema({ - explicit: [ - __nccwpck_require__(52672), - __nccwpck_require__(5490), - __nccwpck_require__(31173) - ] -}); + return (new RegExp('^' + regex + '$', 'gi')).test(v) + } + + if (true) { + if ( true && module.exports) { + exports = module.exports = isBase64 + } + exports.isBase64 = isBase64 + } else {} +})(this); /***/ }), -/***/ 1571: +/***/ 56873: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. +var has = __nccwpck_require__(76339); +function specifierIncluded(current, specifier) { + var nodeParts = current.split('.'); + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + for (var i = 0; i < 3; ++i) { + var cur = parseInt(nodeParts[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } + if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} -var Schema = __nccwpck_require__(66514); - - -module.exports = new Schema({ - include: [ - __nccwpck_require__(66037) - ], - implicit: [ - __nccwpck_require__(22671), - __nccwpck_require__(94675), - __nccwpck_require__(89963), - __nccwpck_require__(15564) - ] -}); - +function matchesRange(current, range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { + return false; + } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(current, specifiers[i])) { + return false; + } + } + return true; +} -/***/ }), +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } -/***/ 30967: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node && process.versions.node + : nodeVersion; -"use strict"; + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(current, specifierValue[i])) { + return true; + } + } + return false; + } + return matchesRange(current, specifierValue); +} -var YAMLException = __nccwpck_require__(65199); +var data = __nccwpck_require__(93991); -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'defaultStyle', - 'styleAliases' -]; +module.exports = function isCore(x, nodeVersion) { + return has(data, x) && versionIncluded(nodeVersion, data[x]); +}; -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; -function compileStyleAliases(map) { - var result = {}; +/***/ }), - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } +/***/ 64882: +/***/ ((module) => { - return result; -} +"use strict"; +/* eslint-disable yoda */ -function Type(tag, options) { - options = options || {}; - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } - // TODO: Add tag format check. - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} + return false; +}; -module.exports = Type; +module.exports = isFullwidthCodePoint; +module.exports.default = isFullwidthCodePoint; /***/ }), -/***/ 32551: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -/*eslint-disable no-bitwise*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); -var NodeBuffer; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ -try { - // A trick for browserified version, to not include `Buffer` shim - var _require = require; - NodeBuffer = _require('buffer').Buffer; -} catch (__) {} +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} -var Type = __nccwpck_require__(30967); +function isPlainObject(o) { + var ctor,prot; + if (isObject(o) === false) return false; -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; -function resolveYamlBinary(data) { - if (data === null) return false; + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + // Most likely a plain Object + return true; +} - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); +exports.isPlainObject = isPlainObject; - // Skip CR/LF - if (code > 64) continue; - // Fail on illegal characters - if (code < 0) return false; +/***/ }), - bitlen += 6; - } +/***/ 87783: +/***/ ((__unused_webpack_module, exports) => { - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} +(function(exports) { + "use strict"; -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; + function isArray(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Array]"; + } else { + return false; + } + } - // Collect by 6*4 bits (3 bytes) + function isObject(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } else { + return false; + } + } - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); + function strictDeepEqual(first, second) { + // Check the scalar case first. + if (first === second) { + return true; } - bits = (bits << 6) | map.indexOf(input.charAt(idx)); + // Check if they are the same type. + var firstType = Object.prototype.toString.call(first); + if (firstType !== Object.prototype.toString.call(second)) { + return false; + } + // We know that first and second have the same type so we can just check the + // first type from now on. + if (isArray(first) === true) { + // Short circuit if they're not the same length; + if (first.length !== second.length) { + return false; + } + for (var i = 0; i < first.length; i++) { + if (strictDeepEqual(first[i], second[i]) === false) { + return false; + } + } + return true; + } + if (isObject(first) === true) { + // An object is equal if it has the same key/value pairs. + var keysSeen = {}; + for (var key in first) { + if (hasOwnProperty.call(first, key)) { + if (strictDeepEqual(first[key], second[key]) === false) { + return false; + } + keysSeen[key] = true; + } + } + // Now check that there aren't any keys in second that weren't + // in first. + for (var key2 in second) { + if (hasOwnProperty.call(second, key2)) { + if (keysSeen[key2] !== true) { + return false; + } + } + } + return true; + } + return false; } - // Dump tail - - tailbits = (max % 4) * 6; + function isFalse(obj) { + // From the spec: + // A false value corresponds to the following values: + // Empty list + // Empty object + // Empty string + // False boolean + // null value - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); + // First check the scalar values. + if (obj === "" || obj === false || obj === null) { + return true; + } else if (isArray(obj) && obj.length === 0) { + // Check for an empty array. + return true; + } else if (isObject(obj)) { + // Check for an empty object. + for (var key in obj) { + // If there are any keys, then + // the object is not empty so the object + // is not false. + if (obj.hasOwnProperty(key)) { + return false; + } + } + return true; + } else { + return false; + } } - // Wrap into Buffer for NodeJS and leave Array for browser - if (NodeBuffer) { - // Support node 6.+ Buffer API when available - return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + function objValues(obj) { + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; } - return result; -} - -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } + function merge(a, b) { + var merged = {}; + for (var key in a) { + merged[key] = a[key]; + } + for (var key2 in b) { + merged[key2] = b[key2]; + } + return merged; + } - bits = (bits << 8) + object[idx]; + var trimLeft; + if (typeof String.prototype.trimLeft === "function") { + trimLeft = function(str) { + return str.trimLeft(); + }; + } else { + trimLeft = function(str) { + return str.match(/^\s*(.*)/)[1]; + }; } - // Dump tail + // Type constants used to define functions. + var TYPE_NUMBER = 0; + var TYPE_ANY = 1; + var TYPE_STRING = 2; + var TYPE_ARRAY = 3; + var TYPE_OBJECT = 4; + var TYPE_BOOLEAN = 5; + var TYPE_EXPREF = 6; + var TYPE_NULL = 7; + var TYPE_ARRAY_NUMBER = 8; + var TYPE_ARRAY_STRING = 9; - tail = max % 3; + var TOK_EOF = "EOF"; + var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; + var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; + var TOK_RBRACKET = "Rbracket"; + var TOK_RPAREN = "Rparen"; + var TOK_COMMA = "Comma"; + var TOK_COLON = "Colon"; + var TOK_RBRACE = "Rbrace"; + var TOK_NUMBER = "Number"; + var TOK_CURRENT = "Current"; + var TOK_EXPREF = "Expref"; + var TOK_PIPE = "Pipe"; + var TOK_OR = "Or"; + var TOK_AND = "And"; + var TOK_EQ = "EQ"; + var TOK_GT = "GT"; + var TOK_LT = "LT"; + var TOK_GTE = "GTE"; + var TOK_LTE = "LTE"; + var TOK_NE = "NE"; + var TOK_FLATTEN = "Flatten"; + var TOK_STAR = "Star"; + var TOK_FILTER = "Filter"; + var TOK_DOT = "Dot"; + var TOK_NOT = "Not"; + var TOK_LBRACE = "Lbrace"; + var TOK_LBRACKET = "Lbracket"; + var TOK_LPAREN= "Lparen"; + var TOK_LITERAL= "Literal"; - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } + // The "&", "[", "<", ">" tokens + // are not in basicToken because + // there are two token variants + // ("&&", "[?", "<=", ">="). This is specially handled + // below. - return result; -} + var basicTokens = { + ".": TOK_DOT, + "*": TOK_STAR, + ",": TOK_COMMA, + ":": TOK_COLON, + "{": TOK_LBRACE, + "}": TOK_RBRACE, + "]": TOK_RBRACKET, + "(": TOK_LPAREN, + ")": TOK_RPAREN, + "@": TOK_CURRENT + }; -function isBinary(object) { - return NodeBuffer && NodeBuffer.isBuffer(object); -} + var operatorStartToken = { + "<": true, + ">": true, + "=": true, + "!": true + }; -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); + var skipChars = { + " ": true, + "\t": true, + "\n": true + }; -/***/ }), + function isAlpha(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_"; + } -/***/ 94675: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function isNum(ch) { + return (ch >= "0" && ch <= "9") || + ch === "-"; + } + function isAlphaNum(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + (ch >= "0" && ch <= "9") || + ch === "_"; + } -"use strict"; + function Lexer() { + } + Lexer.prototype = { + tokenize: function(stream) { + var tokens = []; + this._current = 0; + var start; + var identifier; + var token; + while (this._current < stream.length) { + if (isAlpha(stream[this._current])) { + start = this._current; + identifier = this._consumeUnquotedIdentifier(stream); + tokens.push({type: TOK_UNQUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (basicTokens[stream[this._current]] !== undefined) { + tokens.push({type: basicTokens[stream[this._current]], + value: stream[this._current], + start: this._current}); + this._current++; + } else if (isNum(stream[this._current])) { + token = this._consumeNumber(stream); + tokens.push(token); + } else if (stream[this._current] === "[") { + // No need to increment this._current. This happens + // in _consumeLBracket + token = this._consumeLBracket(stream); + tokens.push(token); + } else if (stream[this._current] === "\"") { + start = this._current; + identifier = this._consumeQuotedIdentifier(stream); + tokens.push({type: TOK_QUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (stream[this._current] === "'") { + start = this._current; + identifier = this._consumeRawStringLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: identifier, + start: start}); + } else if (stream[this._current] === "`") { + start = this._current; + var literal = this._consumeLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: literal, + start: start}); + } else if (operatorStartToken[stream[this._current]] !== undefined) { + tokens.push(this._consumeOperator(stream)); + } else if (skipChars[stream[this._current]] !== undefined) { + // Ignore whitespace. + this._current++; + } else if (stream[this._current] === "&") { + start = this._current; + this._current++; + if (stream[this._current] === "&") { + this._current++; + tokens.push({type: TOK_AND, value: "&&", start: start}); + } else { + tokens.push({type: TOK_EXPREF, value: "&", start: start}); + } + } else if (stream[this._current] === "|") { + start = this._current; + this._current++; + if (stream[this._current] === "|") { + this._current++; + tokens.push({type: TOK_OR, value: "||", start: start}); + } else { + tokens.push({type: TOK_PIPE, value: "|", start: start}); + } + } else { + var error = new Error("Unknown character:" + stream[this._current]); + error.name = "LexerError"; + throw error; + } + } + return tokens; + }, + _consumeUnquotedIdentifier: function(stream) { + var start = this._current; + this._current++; + while (this._current < stream.length && isAlphaNum(stream[this._current])) { + this._current++; + } + return stream.slice(start, this._current); + }, -var Type = __nccwpck_require__(30967); + _consumeQuotedIdentifier: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "\"" && this._current < maxLength) { + // You can escape a double quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "\"")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + return JSON.parse(stream.slice(start, this._current)); + }, -function resolveYamlBoolean(data) { - if (data === null) return false; + _consumeRawStringLiteral: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "'" && this._current < maxLength) { + // You can escape a single quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "'")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + var literal = stream.slice(start + 1, this._current - 1); + return literal.replace("\\'", "'"); + }, - var max = data.length; + _consumeNumber: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (isNum(stream[this._current]) && this._current < maxLength) { + this._current++; + } + var value = parseInt(stream.slice(start, this._current)); + return {type: TOK_NUMBER, value: value, start: start}; + }, - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} + _consumeLBracket: function(stream) { + var start = this._current; + this._current++; + if (stream[this._current] === "?") { + this._current++; + return {type: TOK_FILTER, value: "[?", start: start}; + } else if (stream[this._current] === "]") { + this._current++; + return {type: TOK_FLATTEN, value: "[]", start: start}; + } else { + return {type: TOK_LBRACKET, value: "[", start: start}; + } + }, -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} + _consumeOperator: function(stream) { + var start = this._current; + var startingChar = stream[start]; + this._current++; + if (startingChar === "!") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_NE, value: "!=", start: start}; + } else { + return {type: TOK_NOT, value: "!", start: start}; + } + } else if (startingChar === "<") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_LTE, value: "<=", start: start}; + } else { + return {type: TOK_LT, value: "<", start: start}; + } + } else if (startingChar === ">") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_GTE, value: ">=", start: start}; + } else { + return {type: TOK_GT, value: ">", start: start}; + } + } else if (startingChar === "=") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_EQ, value: "==", start: start}; + } + } + }, -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} + _consumeLiteral: function(stream) { + this._current++; + var start = this._current; + var maxLength = stream.length; + var literal; + while(stream[this._current] !== "`" && this._current < maxLength) { + // You can escape a literal char or you can escape the escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "`")) { + current += 2; + } else { + current++; + } + this._current = current; + } + var literalString = trimLeft(stream.slice(start, this._current)); + literalString = literalString.replace("\\`", "`"); + if (this._looksLikeJSON(literalString)) { + literal = JSON.parse(literalString); + } else { + // Try to JSON parse it as "" + literal = JSON.parse("\"" + literalString + "\""); + } + // +1 gets us to the ending "`", +1 to move on to the next char. + this._current++; + return literal; + }, -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); + _looksLikeJSON: function(literalString) { + var startingChars = "[{\""; + var jsonLiterals = ["true", "false", "null"]; + var numberLooking = "-0123456789"; + if (literalString === "") { + return false; + } else if (startingChars.indexOf(literalString[0]) >= 0) { + return true; + } else if (jsonLiterals.indexOf(literalString) >= 0) { + return true; + } else if (numberLooking.indexOf(literalString[0]) >= 0) { + try { + JSON.parse(literalString); + return true; + } catch (ex) { + return false; + } + } else { + return false; + } + } + }; -/***/ }), + var bindingPower = {}; + bindingPower[TOK_EOF] = 0; + bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; + bindingPower[TOK_QUOTEDIDENTIFIER] = 0; + bindingPower[TOK_RBRACKET] = 0; + bindingPower[TOK_RPAREN] = 0; + bindingPower[TOK_COMMA] = 0; + bindingPower[TOK_RBRACE] = 0; + bindingPower[TOK_NUMBER] = 0; + bindingPower[TOK_CURRENT] = 0; + bindingPower[TOK_EXPREF] = 0; + bindingPower[TOK_PIPE] = 1; + bindingPower[TOK_OR] = 2; + bindingPower[TOK_AND] = 3; + bindingPower[TOK_EQ] = 5; + bindingPower[TOK_GT] = 5; + bindingPower[TOK_LT] = 5; + bindingPower[TOK_GTE] = 5; + bindingPower[TOK_LTE] = 5; + bindingPower[TOK_NE] = 5; + bindingPower[TOK_FLATTEN] = 9; + bindingPower[TOK_STAR] = 20; + bindingPower[TOK_FILTER] = 21; + bindingPower[TOK_DOT] = 40; + bindingPower[TOK_NOT] = 45; + bindingPower[TOK_LBRACE] = 50; + bindingPower[TOK_LBRACKET] = 55; + bindingPower[TOK_LPAREN] = 60; -/***/ 15564: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function Parser() { + } -"use strict"; + Parser.prototype = { + parse: function(expression) { + this._loadTokens(expression); + this.index = 0; + var ast = this.expression(0); + if (this._lookahead(0) !== TOK_EOF) { + var t = this._lookaheadToken(0); + var error = new Error( + "Unexpected token type: " + t.type + ", value: " + t.value); + error.name = "ParserError"; + throw error; + } + return ast; + }, + _loadTokens: function(expression) { + var lexer = new Lexer(); + var tokens = lexer.tokenize(expression); + tokens.push({type: TOK_EOF, value: "", start: expression.length}); + this.tokens = tokens; + }, -var common = __nccwpck_require__(59136); -var Type = __nccwpck_require__(30967); + expression: function(rbp) { + var leftToken = this._lookaheadToken(0); + this._advance(); + var left = this.nud(leftToken); + var currentToken = this._lookahead(0); + while (rbp < bindingPower[currentToken]) { + this._advance(); + left = this.led(currentToken, left); + currentToken = this._lookahead(0); + } + return left; + }, -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // 20:59 - '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); + _lookahead: function(number) { + return this.tokens[this.index + number].type; + }, -function resolveYamlFloat(data) { - if (data === null) return false; + _lookaheadToken: function(number) { + return this.tokens[this.index + number]; + }, - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } + _advance: function() { + this.index++; + }, - return true; -} + nud: function(token) { + var left; + var right; + var expression; + switch (token.type) { + case TOK_LITERAL: + return {type: "Literal", value: token.value}; + case TOK_UNQUOTEDIDENTIFIER: + return {type: "Field", name: token.value}; + case TOK_QUOTEDIDENTIFIER: + var node = {type: "Field", name: token.value}; + if (this._lookahead(0) === TOK_LPAREN) { + throw new Error("Quoted identifier not allowed for function names."); + } else { + return node; + } + break; + case TOK_NOT: + right = this.expression(bindingPower.Not); + return {type: "NotExpression", children: [right]}; + case TOK_STAR: + left = {type: "Identity"}; + right = null; + if (this._lookahead(0) === TOK_RBRACKET) { + // This can happen in a multiselect, + // [a, b, *] + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Star); + } + return {type: "ValueProjection", children: [left, right]}; + case TOK_FILTER: + return this.led(token.type, {type: "Identity"}); + case TOK_LBRACE: + return this._parseMultiselectHash(); + case TOK_FLATTEN: + left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; + right = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [left, right]}; + case TOK_LBRACKET: + if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice({type: "Identity"}, right); + } else if (this._lookahead(0) === TOK_STAR && + this._lookahead(1) === TOK_RBRACKET) { + this._advance(); + this._advance(); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", + children: [{type: "Identity"}, right]}; + } else { + return this._parseMultiselectList(); + } + break; + case TOK_CURRENT: + return {type: TOK_CURRENT}; + case TOK_EXPREF: + expression = this.expression(bindingPower.Expref); + return {type: "ExpressionReference", children: [expression]}; + case TOK_LPAREN: + var args = []; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + args.push(expression); + } + this._match(TOK_RPAREN); + return args[0]; + default: + this._errorToken(token); + } + }, -function constructYamlFloat(data) { - var value, sign, base, digits; + led: function(tokenName, left) { + var right; + switch(tokenName) { + case TOK_DOT: + var rbp = bindingPower.Dot; + if (this._lookahead(0) !== TOK_STAR) { + right = this._parseDotRHS(rbp); + return {type: "Subexpression", children: [left, right]}; + } else { + // Creating a projection. + this._advance(); + right = this._parseProjectionRHS(rbp); + return {type: "ValueProjection", children: [left, right]}; + } + break; + case TOK_PIPE: + right = this.expression(bindingPower.Pipe); + return {type: TOK_PIPE, children: [left, right]}; + case TOK_OR: + right = this.expression(bindingPower.Or); + return {type: "OrExpression", children: [left, right]}; + case TOK_AND: + right = this.expression(bindingPower.And); + return {type: "AndExpression", children: [left, right]}; + case TOK_LPAREN: + var name = left.name; + var args = []; + var expression, node; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } + args.push(expression); + } + this._match(TOK_RPAREN); + node = {type: "Function", name: name, children: args}; + return node; + case TOK_FILTER: + var condition = this.expression(0); + this._match(TOK_RBRACKET); + if (this._lookahead(0) === TOK_FLATTEN) { + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Filter); + } + return {type: "FilterProjection", children: [left, right, condition]}; + case TOK_FLATTEN: + var leftNode = {type: TOK_FLATTEN, children: [left]}; + var rightNode = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [leftNode, rightNode]}; + case TOK_EQ: + case TOK_NE: + case TOK_GT: + case TOK_GTE: + case TOK_LT: + case TOK_LTE: + return this._parseComparator(left, tokenName); + case TOK_LBRACKET: + var token = this._lookaheadToken(0); + if (token.type === TOK_NUMBER || token.type === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice(left, right); + } else { + this._match(TOK_STAR); + this._match(TOK_RBRACKET); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", children: [left, right]}; + } + break; + default: + this._errorToken(this._lookaheadToken(0)); + } + }, - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; + _match: function(tokenType) { + if (this._lookahead(0) === tokenType) { + this._advance(); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Expected " + tokenType + ", got: " + t.type); + error.name = "ParserError"; + throw error; + } + }, - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } + _errorToken: function(token) { + var error = new Error("Invalid token (" + + token.type + "): \"" + + token.value + "\""); + error.name = "ParserError"; + throw error; + }, - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - } else if (value === '.nan') { - return NaN; + _parseIndexExpression: function() { + if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { + return this._parseSliceExpression(); + } else { + var node = { + type: "Index", + value: this._lookaheadToken(0).value}; + this._advance(); + this._match(TOK_RBRACKET); + return node; + } + }, - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); + _projectIfSlice: function(left, right) { + var indexExpr = {type: "IndexExpression", children: [left, right]}; + if (right.type === "Slice") { + return { + type: "Projection", + children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] + }; + } else { + return indexExpr; + } + }, - value = 0.0; - base = 1; + _parseSliceExpression: function() { + // [start:end:step] where each part is optional, as well as the last + // colon. + var parts = [null, null, null]; + var index = 0; + var currentToken = this._lookahead(0); + while (currentToken !== TOK_RBRACKET && index < 3) { + if (currentToken === TOK_COLON) { + index++; + this._advance(); + } else if (currentToken === TOK_NUMBER) { + parts[index] = this._lookaheadToken(0).value; + this._advance(); + } else { + var t = this._lookahead(0); + var error = new Error("Syntax error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "Parsererror"; + throw error; + } + currentToken = this._lookahead(0); + } + this._match(TOK_RBRACKET); + return { + type: "Slice", + children: parts + }; + }, - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); + _parseComparator: function(left, comparator) { + var right = this.expression(bindingPower[comparator]); + return {type: "Comparator", name: comparator, children: [left, right]}; + }, - return sign * value; + _parseDotRHS: function(rbp) { + var lookahead = this._lookahead(0); + var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; + if (exprTokens.indexOf(lookahead) >= 0) { + return this.expression(rbp); + } else if (lookahead === TOK_LBRACKET) { + this._match(TOK_LBRACKET); + return this._parseMultiselectList(); + } else if (lookahead === TOK_LBRACE) { + this._match(TOK_LBRACE); + return this._parseMultiselectHash(); + } + }, - } - return sign * parseFloat(value, 10); -} + _parseProjectionRHS: function(rbp) { + var right; + if (bindingPower[this._lookahead(0)] < 10) { + right = {type: "Identity"}; + } else if (this._lookahead(0) === TOK_LBRACKET) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_FILTER) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_DOT) { + this._match(TOK_DOT); + right = this._parseDotRHS(rbp); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Sytanx error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "ParserError"; + throw error; + } + return right; + }, + _parseMultiselectList: function() { + var expressions = []; + while (this._lookahead(0) !== TOK_RBRACKET) { + var expression = this.expression(0); + expressions.push(expression); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + if (this._lookahead(0) === TOK_RBRACKET) { + throw new Error("Unexpected token Rbracket"); + } + } + } + this._match(TOK_RBRACKET); + return {type: "MultiSelectList", children: expressions}; + }, -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + _parseMultiselectHash: function() { + var pairs = []; + var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; + var keyToken, keyName, value, node; + for (;;) { + keyToken = this._lookaheadToken(0); + if (identifierTypes.indexOf(keyToken.type) < 0) { + throw new Error("Expecting an identifier token, got: " + + keyToken.type); + } + keyName = keyToken.value; + this._advance(); + this._match(TOK_COLON); + value = this.expression(0); + node = {type: "KeyValuePair", name: keyName, value: value}; + pairs.push(node); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } else if (this._lookahead(0) === TOK_RBRACE) { + this._match(TOK_RBRACE); + break; + } + } + return {type: "MultiSelectHash", children: pairs}; + } + }; -function representYamlFloat(object, style) { - var res; - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; + function TreeInterpreter(runtime) { + this.runtime = runtime; } - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack + TreeInterpreter.prototype = { + search: function(node, value) { + return this.visit(node, value); + }, - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} + visit: function(node, value) { + var matched, current, result, first, second, field, left, right, collected, i; + switch (node.type) { + case "Field": + if (value === null ) { + return null; + } else if (isObject(value)) { + field = value[node.name]; + if (field === undefined) { + return null; + } else { + return field; + } + } else { + return null; + } + break; + case "Subexpression": + result = this.visit(node.children[0], value); + for (i = 1; i < node.children.length; i++) { + result = this.visit(node.children[1], result); + if (result === null) { + return null; + } + } + return result; + case "IndexExpression": + left = this.visit(node.children[0], value); + right = this.visit(node.children[1], left); + return right; + case "Index": + if (!isArray(value)) { + return null; + } + var index = node.value; + if (index < 0) { + index = value.length + index; + } + result = value[index]; + if (result === undefined) { + result = null; + } + return result; + case "Slice": + if (!isArray(value)) { + return null; + } + var sliceParams = node.children.slice(0); + var computed = this.computeSliceParams(value.length, sliceParams); + var start = computed[0]; + var stop = computed[1]; + var step = computed[2]; + result = []; + if (step > 0) { + for (i = start; i < stop; i += step) { + result.push(value[i]); + } + } else { + for (i = start; i > stop; i += step) { + result.push(value[i]); + } + } + return result; + case "Projection": + // Evaluate left child. + var base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + collected = []; + for (i = 0; i < base.length; i++) { + current = this.visit(node.children[1], base[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "ValueProjection": + // Evaluate left child. + base = this.visit(node.children[0], value); + if (!isObject(base)) { + return null; + } + collected = []; + var values = objValues(base); + for (i = 0; i < values.length; i++) { + current = this.visit(node.children[1], values[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "FilterProjection": + base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + var filtered = []; + var finalResults = []; + for (i = 0; i < base.length; i++) { + matched = this.visit(node.children[2], base[i]); + if (!isFalse(matched)) { + filtered.push(base[i]); + } + } + for (var j = 0; j < filtered.length; j++) { + current = this.visit(node.children[1], filtered[j]); + if (current !== null) { + finalResults.push(current); + } + } + return finalResults; + case "Comparator": + first = this.visit(node.children[0], value); + second = this.visit(node.children[1], value); + switch(node.name) { + case TOK_EQ: + result = strictDeepEqual(first, second); + break; + case TOK_NE: + result = !strictDeepEqual(first, second); + break; + case TOK_GT: + result = first > second; + break; + case TOK_GTE: + result = first >= second; + break; + case TOK_LT: + result = first < second; + break; + case TOK_LTE: + result = first <= second; + break; + default: + throw new Error("Unknown comparator: " + node.name); + } + return result; + case TOK_FLATTEN: + var original = this.visit(node.children[0], value); + if (!isArray(original)) { + return null; + } + var merged = []; + for (i = 0; i < original.length; i++) { + current = original[i]; + if (isArray(current)) { + merged.push.apply(merged, current); + } else { + merged.push(current); + } + } + return merged; + case "Identity": + return value; + case "MultiSelectList": + if (value === null) { + return null; + } + collected = []; + for (i = 0; i < node.children.length; i++) { + collected.push(this.visit(node.children[i], value)); + } + return collected; + case "MultiSelectHash": + if (value === null) { + return null; + } + collected = {}; + var child; + for (i = 0; i < node.children.length; i++) { + child = node.children[i]; + collected[child.name] = this.visit(child.value, value); + } + return collected; + case "OrExpression": + matched = this.visit(node.children[0], value); + if (isFalse(matched)) { + matched = this.visit(node.children[1], value); + } + return matched; + case "AndExpression": + first = this.visit(node.children[0], value); -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} + if (isFalse(first) === true) { + return first; + } + return this.visit(node.children[1], value); + case "NotExpression": + first = this.visit(node.children[0], value); + return isFalse(first); + case "Literal": + return node.value; + case TOK_PIPE: + left = this.visit(node.children[0], value); + return this.visit(node.children[1], left); + case TOK_CURRENT: + return value; + case "Function": + var resolvedArgs = []; + for (i = 0; i < node.children.length; i++) { + resolvedArgs.push(this.visit(node.children[i], value)); + } + return this.runtime.callFunction(node.name, resolvedArgs); + case "ExpressionReference": + var refNode = node.children[0]; + // Tag the node with a specific attribute so the type + // checker verify the type. + refNode.jmespathType = TOK_EXPREF; + return refNode; + default: + throw new Error("Unknown node type: " + node.type); + } + }, -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); + computeSliceParams: function(arrayLength, sliceParams) { + var start = sliceParams[0]; + var stop = sliceParams[1]; + var step = sliceParams[2]; + var computed = [null, null, null]; + if (step === null) { + step = 1; + } else if (step === 0) { + var error = new Error("Invalid slice, step cannot be 0"); + error.name = "RuntimeError"; + throw error; + } + var stepValueNegative = step < 0 ? true : false; + if (start === null) { + start = stepValueNegative ? arrayLength - 1 : 0; + } else { + start = this.capSliceRange(arrayLength, start, step); + } -/***/ }), + if (stop === null) { + stop = stepValueNegative ? -1 : arrayLength; + } else { + stop = this.capSliceRange(arrayLength, stop, step); + } + computed[0] = start; + computed[1] = stop; + computed[2] = step; + return computed; + }, -/***/ 89963: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + capSliceRange: function(arrayLength, actualValue, step) { + if (actualValue < 0) { + actualValue += arrayLength; + if (actualValue < 0) { + actualValue = step < 0 ? -1 : 0; + } + } else if (actualValue >= arrayLength) { + actualValue = step < 0 ? arrayLength - 1 : arrayLength; + } + return actualValue; + } -"use strict"; + }; + function Runtime(interpreter) { + this._interpreter = interpreter; + this.functionTable = { + // name: [function, ] + // The can be: + // + // { + // args: [[type1, type2], [type1, type2]], + // variadic: true|false + // } + // + // Each arg in the arg list is a list of valid types + // (if the function is overloaded and supports multiple + // types. If the type is "any" then no type checking + // occurs on the argument. Variadic is optional + // and if not provided is assumed to be false. + abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, + avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, + contains: { + _func: this._functionContains, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, + {types: [TYPE_ANY]}]}, + "ends_with": { + _func: this._functionEndsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, + length: { + _func: this._functionLength, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, + map: { + _func: this._functionMap, + _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, + max: { + _func: this._functionMax, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "merge": { + _func: this._functionMerge, + _signature: [{types: [TYPE_OBJECT], variadic: true}] + }, + "max_by": { + _func: this._functionMaxBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + "starts_with": { + _func: this._functionStartsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + min: { + _func: this._functionMin, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "min_by": { + _func: this._functionMinBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, + keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, + values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, + sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, + "sort_by": { + _func: this._functionSortBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + join: { + _func: this._functionJoin, + _signature: [ + {types: [TYPE_STRING]}, + {types: [TYPE_ARRAY_STRING]} + ] + }, + reverse: { + _func: this._functionReverse, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, + "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, + "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, + "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, + "not_null": { + _func: this._functionNotNull, + _signature: [{types: [TYPE_ANY], variadic: true}] + } + }; + } -var common = __nccwpck_require__(59136); -var Type = __nccwpck_require__(30967); + Runtime.prototype = { + callFunction: function(name, resolvedArgs) { + var functionEntry = this.functionTable[name]; + if (functionEntry === undefined) { + throw new Error("Unknown function: " + name + "()"); + } + this._validateArgs(name, resolvedArgs, functionEntry._signature); + return functionEntry._func.call(this, resolvedArgs); + }, -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} + _validateArgs: function(name, args, signature) { + // Validating the args requires validating + // the correct arity and the correct type of each arg. + // If the last argument is declared as variadic, then we need + // a minimum number of args to be required. Otherwise it has to + // be an exact amount. + var pluralized; + if (signature[signature.length - 1].variadic) { + if (args.length < signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes at least" + signature.length + pluralized + + " but received " + args.length); + } + } else if (args.length !== signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes " + signature.length + pluralized + + " but received " + args.length); + } + var currentSpec; + var actualType; + var typeMatched; + for (var i = 0; i < signature.length; i++) { + typeMatched = false; + currentSpec = signature[i].types; + actualType = this._getTypeName(args[i]); + for (var j = 0; j < currentSpec.length; j++) { + if (this._typeMatches(actualType, currentSpec[j], args[i])) { + typeMatched = true; + break; + } + } + if (!typeMatched) { + throw new Error("TypeError: " + name + "() " + + "expected argument " + (i + 1) + + " to be type " + currentSpec + + " but received type " + actualType + + " instead."); + } + } + }, -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} + _typeMatches: function(actual, expected, argValue) { + if (expected === TYPE_ANY) { + return true; + } + if (expected === TYPE_ARRAY_STRING || + expected === TYPE_ARRAY_NUMBER || + expected === TYPE_ARRAY) { + // The expected type can either just be array, + // or it can require a specific subtype (array of numbers). + // + // The simplest case is if "array" with no subtype is specified. + if (expected === TYPE_ARRAY) { + return actual === TYPE_ARRAY; + } else if (actual === TYPE_ARRAY) { + // Otherwise we need to check subtypes. + // I think this has potential to be improved. + var subtype; + if (expected === TYPE_ARRAY_NUMBER) { + subtype = TYPE_NUMBER; + } else if (expected === TYPE_ARRAY_STRING) { + subtype = TYPE_STRING; + } + for (var i = 0; i < argValue.length; i++) { + if (!this._typeMatches( + this._getTypeName(argValue[i]), subtype, + argValue[i])) { + return false; + } + } + return true; + } + } else { + return actual === expected; + } + }, + _getTypeName: function(obj) { + switch (Object.prototype.toString.call(obj)) { + case "[object String]": + return TYPE_STRING; + case "[object Number]": + return TYPE_NUMBER; + case "[object Array]": + return TYPE_ARRAY; + case "[object Boolean]": + return TYPE_BOOLEAN; + case "[object Null]": + return TYPE_NULL; + case "[object Object]": + // Check if it's an expref. If it has, it's been + // tagged with a jmespathType attr of 'Expref'; + if (obj.jmespathType === TOK_EXPREF) { + return TYPE_EXPREF; + } else { + return TYPE_OBJECT; + } + } + }, -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} + _functionStartsWith: function(resolvedArgs) { + return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; + }, -function resolveYamlInteger(data) { - if (data === null) return false; + _functionEndsWith: function(resolvedArgs) { + var searchStr = resolvedArgs[0]; + var suffix = resolvedArgs[1]; + return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; + }, - var max = data.length, - index = 0, - hasDigits = false, - ch; + _functionReverse: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + if (typeName === TYPE_STRING) { + var originalStr = resolvedArgs[0]; + var reversedStr = ""; + for (var i = originalStr.length - 1; i >= 0; i--) { + reversedStr += originalStr[i]; + } + return reversedStr; + } else { + var reversedArray = resolvedArgs[0].slice(0); + reversedArray.reverse(); + return reversedArray; + } + }, - if (!max) return false; + _functionAbs: function(resolvedArgs) { + return Math.abs(resolvedArgs[0]); + }, - ch = data[index]; + _functionCeil: function(resolvedArgs) { + return Math.ceil(resolvedArgs[0]); + }, - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } + _functionAvg: function(resolvedArgs) { + var sum = 0; + var inputArray = resolvedArgs[0]; + for (var i = 0; i < inputArray.length; i++) { + sum += inputArray[i]; + } + return sum / inputArray.length; + }, - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; + _functionContains: function(resolvedArgs) { + return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; + }, - // base 2, base 8, base 16 + _functionFloor: function(resolvedArgs) { + return Math.floor(resolvedArgs[0]); + }, - if (ch === 'b') { - // base 2 - index++; + _functionLength: function(resolvedArgs) { + if (!isObject(resolvedArgs[0])) { + return resolvedArgs[0].length; + } else { + // As far as I can tell, there's no way to get the length + // of an object without O(n) iteration through the object. + return Object.keys(resolvedArgs[0]).length; + } + }, - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; + _functionMap: function(resolvedArgs) { + var mapped = []; + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[0]; + var elements = resolvedArgs[1]; + for (var i = 0; i < elements.length; i++) { + mapped.push(interpreter.visit(exprefNode, elements[i])); } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; + return mapped; + }, - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; + _functionMerge: function(resolvedArgs) { + var merged = {}; + for (var i = 0; i < resolvedArgs.length; i++) { + var current = resolvedArgs[i]; + for (var key in current) { + merged[key] = current[key]; + } } - return hasDigits && ch !== '_'; - } + return merged; + }, - // base 8 - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } + _functionMax: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.max.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var maxElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (maxElement.localeCompare(elements[i]) < 0) { + maxElement = elements[i]; + } + } + return maxElement; + } + } else { + return null; + } + }, - // base 10 (except 0) or base 60 + _functionMin: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.min.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var minElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (elements[i].localeCompare(minElement) < 0) { + minElement = elements[i]; + } + } + return minElement; + } + } else { + return null; + } + }, - // value should not start with `_`; - if (ch === '_') return false; + _functionSum: function(resolvedArgs) { + var sum = 0; + var listToSum = resolvedArgs[0]; + for (var i = 0; i < listToSum.length; i++) { + sum += listToSum[i]; + } + return sum; + }, - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch === ':') break; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; - } + _functionType: function(resolvedArgs) { + switch (this._getTypeName(resolvedArgs[0])) { + case TYPE_NUMBER: + return "number"; + case TYPE_STRING: + return "string"; + case TYPE_ARRAY: + return "array"; + case TYPE_OBJECT: + return "object"; + case TYPE_BOOLEAN: + return "boolean"; + case TYPE_EXPREF: + return "expref"; + case TYPE_NULL: + return "null"; + } + }, - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; + _functionKeys: function(resolvedArgs) { + return Object.keys(resolvedArgs[0]); + }, - // if !base60 - done; - if (ch !== ':') return true; + _functionValues: function(resolvedArgs) { + var obj = resolvedArgs[0]; + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + }, - // base60 almost not used, no needs to optimize - return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); -} + _functionJoin: function(resolvedArgs) { + var joinChar = resolvedArgs[0]; + var listJoin = resolvedArgs[1]; + return listJoin.join(joinChar); + }, -function constructYamlInteger(data) { - var value = data, sign = 1, ch, base, digits = []; + _functionToArray: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { + return resolvedArgs[0]; + } else { + return [resolvedArgs[0]]; + } + }, - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } + _functionToString: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { + return resolvedArgs[0]; + } else { + return JSON.stringify(resolvedArgs[0]); + } + }, - ch = value[0]; + _functionToNumber: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + var convertedValue; + if (typeName === TYPE_NUMBER) { + return resolvedArgs[0]; + } else if (typeName === TYPE_STRING) { + convertedValue = +resolvedArgs[0]; + if (!isNaN(convertedValue)) { + return convertedValue; + } + } + return null; + }, - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } + _functionNotNull: function(resolvedArgs) { + for (var i = 0; i < resolvedArgs.length; i++) { + if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { + return resolvedArgs[i]; + } + } + return null; + }, - if (value === '0') return 0; + _functionSort: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + sortedArray.sort(); + return sortedArray; + }, - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value, 16); - return sign * parseInt(value, 8); - } + _functionSortBy: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + if (sortedArray.length === 0) { + return sortedArray; + } + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[1]; + var requiredType = this._getTypeName( + interpreter.visit(exprefNode, sortedArray[0])); + if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { + throw new Error("TypeError"); + } + var that = this; + // In order to get a stable sort out of an unstable + // sort algorithm, we decorate/sort/undecorate (DSU) + // by creating a new list of [index, element] pairs. + // In the cmp function, if the evaluated elements are + // equal, then the index will be used as the tiebreaker. + // After the decorated list has been sorted, it will be + // undecorated to extract the original elements. + var decorated = []; + for (var i = 0; i < sortedArray.length; i++) { + decorated.push([i, sortedArray[i]]); + } + decorated.sort(function(a, b) { + var exprA = interpreter.visit(exprefNode, a[1]); + var exprB = interpreter.visit(exprefNode, b[1]); + if (that._getTypeName(exprA) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprA)); + } else if (that._getTypeName(exprB) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprB)); + } + if (exprA > exprB) { + return 1; + } else if (exprA < exprB) { + return -1; + } else { + // If they're equal compare the items by their + // order to maintain relative order of equal keys + // (i.e. to get a stable sort). + return a[0] - b[0]; + } + }); + // Undecorate: extract out the original list elements. + for (var j = 0; j < decorated.length; j++) { + sortedArray[j] = decorated[j][1]; + } + return sortedArray; + }, - if (value.indexOf(':') !== -1) { - value.split(':').forEach(function (v) { - digits.unshift(parseInt(v, 10)); - }); + _functionMaxBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var maxNumber = -Infinity; + var maxRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current > maxNumber) { + maxNumber = current; + maxRecord = resolvedArray[i]; + } + } + return maxRecord; + }, - value = 0; - base = 1; + _functionMinBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var minNumber = Infinity; + var minRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current < minNumber) { + minNumber = current; + minRecord = resolvedArray[i]; + } + } + return minRecord; + }, - digits.forEach(function (d) { - value += (d * base); - base *= 60; - }); + createKeyFunction: function(exprefNode, allowedTypes) { + var that = this; + var interpreter = this._interpreter; + var keyFunc = function(x) { + var current = interpreter.visit(exprefNode, x); + if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { + var msg = "TypeError: expected one of " + allowedTypes + + ", received " + that._getTypeName(current); + throw new Error(msg); + } + return current; + }; + return keyFunc; + } - return sign * value; + }; + function compile(stream) { + var parser = new Parser(); + var ast = parser.parse(stream); + return ast; } - return sign * parseInt(value, 10); -} - -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} + function tokenize(stream) { + var lexer = new Lexer(); + return lexer.tokenize(stream); + } -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] + function search(data, expression) { + var parser = new Parser(); + // This needs to be improved. Both the interpreter and runtime depend on + // each other. The runtime needs the interpreter to support exprefs. + // There's likely a clean way to avoid the cyclic dependency. + var runtime = new Runtime(); + var interpreter = new TreeInterpreter(runtime); + runtime._interpreter = interpreter; + var node = parser.parse(expression); + return interpreter.search(node, data); } -}); + + exports.tokenize = tokenize; + exports.compile = compile; + exports.search = search; + exports.strictDeepEqual = strictDeepEqual; +})( false ? 0 : exports); /***/ }), -/***/ 27278: +/***/ 21917: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var esprima; -// Browserified version does not have esprima -// -// 1. For node.js just require module as deps -// 2. For browser try to require mudule via external AMD system. -// If not found - try to fallback to window.esprima. If not -// found too - then fail to parse. -// -try { - // workaround to exclude package from browserify list. - var _require = require; - esprima = _require('esprima'); -} catch (_) { - /* eslint-disable no-redeclare */ - /* global window */ - if (typeof window !== 'undefined') esprima = window.esprima; -} +var yaml = __nccwpck_require__(40916); -var Type = __nccwpck_require__(30967); -function resolveJavascriptFunction(data) { - if (data === null) return false; +module.exports = yaml; - try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - return false; - } +/***/ }), - return true; - } catch (err) { - return false; - } -} +/***/ 40916: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function constructJavascriptFunction(data) { - /*jslint evil:true*/ +"use strict"; - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - throw new Error('Failed to resolve function'); - } - ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); - }); +var loader = __nccwpck_require__(45190); +var dumper = __nccwpck_require__(73034); - body = ast.body[0].expression.body.range; - // Esprima's ranges include the first '{' and the last '}' characters on - // function expressions. So cut them out. - if (ast.body[0].expression.body.type === 'BlockStatement') { - /*eslint-disable no-new-func*/ - return new Function(params, source.slice(body[0] + 1, body[1] - 1)); - } - // ES6 arrow functions can omit the BlockStatement. In that case, just return - // the body. - /*eslint-disable no-new-func*/ - return new Function(params, 'return ' + source.slice(body[0], body[1])); +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; } -function representJavascriptFunction(object /*, style*/) { - return object.toString(); -} -function isFunction(object) { - return Object.prototype.toString.call(object) === '[object Function]'; -} +module.exports.Type = __nccwpck_require__(30967); +module.exports.Schema = __nccwpck_require__(66514); +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(66037); +module.exports.JSON_SCHEMA = __nccwpck_require__(1571); +module.exports.CORE_SCHEMA = __nccwpck_require__(92183); +module.exports.DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); +module.exports.DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.safeLoad = loader.safeLoad; +module.exports.safeLoadAll = loader.safeLoadAll; +module.exports.dump = dumper.dump; +module.exports.safeDump = dumper.safeDump; +module.exports.YAMLException = __nccwpck_require__(65199); -module.exports = new Type('tag:yaml.org,2002:js/function', { - kind: 'scalar', - resolve: resolveJavascriptFunction, - construct: constructJavascriptFunction, - predicate: isFunction, - represent: representJavascriptFunction -}); +// Deprecated schema names from JS-YAML 2.0.x +module.exports.MINIMAL_SCHEMA = __nccwpck_require__(66037); +module.exports.SAFE_SCHEMA = __nccwpck_require__(48949); +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(56874); + +// Deprecated functions from JS-YAML 1.x.x +module.exports.scan = deprecated('scan'); +module.exports.parse = deprecated('parse'); +module.exports.compose = deprecated('compose'); +module.exports.addConstructor = deprecated('addConstructor'); /***/ }), -/***/ 69242: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 59136: +/***/ ((module) => { "use strict"; -var Type = __nccwpck_require__(30967); - -function resolveJavascriptRegExp(data) { - if (data === null) return false; - if (data.length === 0) return false; - - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // if regexp starts with '/' it can have modifiers and must be properly closed - // `/foo/gim` - modifiers tail can be maximum 3 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - - if (modifiers.length > 3) return false; - // if expression starts with /, is should be properly terminated - if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; - } - return true; +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); } -function constructJavascriptRegExp(data) { - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // `/foo/gim` - tail can be maximum 4 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - regexp = regexp.slice(1, regexp.length - modifiers.length - 1); - } - return new RegExp(regexp, modifiers); +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); } -function representJavascriptRegExp(object /*, style*/) { - var result = '/' + object.source + '/'; - if (object.global) result += 'g'; - if (object.multiline) result += 'm'; - if (object.ignoreCase) result += 'i'; +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; - return result; + return [ sequence ]; } -function isRegExp(object) { - return Object.prototype.toString.call(object) === '[object RegExp]'; -} -module.exports = new Type('tag:yaml.org,2002:js/regexp', { - kind: 'scalar', - resolve: resolveJavascriptRegExp, - construct: constructJavascriptRegExp, - predicate: isRegExp, - represent: representJavascriptRegExp -}); +function extend(target, source) { + var index, length, key, sourceKeys; + if (source) { + sourceKeys = Object.keys(source); -/***/ }), + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } -/***/ 25914: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return target; +} -"use strict"; +function repeat(string, count) { + var result = '', cycle; -var Type = __nccwpck_require__(30967); + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } -function resolveJavascriptUndefined() { - return true; + return result; } -function constructJavascriptUndefined() { - /*eslint-disable no-undefined*/ - return undefined; -} -function representJavascriptUndefined() { - return ''; +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } -function isUndefined(object) { - return typeof object === 'undefined'; -} -module.exports = new Type('tag:yaml.org,2002:js/undefined', { - kind: 'scalar', - resolve: resolveJavascriptUndefined, - construct: constructJavascriptUndefined, - predicate: isUndefined, - represent: representJavascriptUndefined -}); +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; /***/ }), -/***/ 31173: +/***/ 73034: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Type = __nccwpck_require__(30967); - -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); - - -/***/ }), - -/***/ 81393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +/*eslint-disable no-use-before-define*/ -var Type = __nccwpck_require__(30967); +var common = __nccwpck_require__(59136); +var YAMLException = __nccwpck_require__(65199); +var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); +var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ +var ESCAPE_SEQUENCES = {}; -/***/ }), +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; -/***/ 22671: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; -"use strict"; +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + if (map === null) return {}; -var Type = __nccwpck_require__(30967); + result = {}; + keys = Object.keys(map); -function resolveYamlNull(data) { - if (data === null) return true; + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); - var max = data.length; + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } -function constructYamlNull() { - return null; -} + result[tag] = style; + } -function isNull(object) { - return object === null; + return result; } -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; } - }, - defaultStyle: 'lowercase' -}); - - -/***/ }), - -/***/ 96668: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function encodeHex(character) { + var string, handle, length; -"use strict"; + string = character.toString(16).toUpperCase(); + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } -var Type = __nccwpck_require__(30967); + return '\\' + handle + common.repeat('0', length - string.length) + string; +} -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; -function resolveYamlOmap(data) { - if (data === null) return true; + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; + this.tag = null; + this.result = ''; - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; + this.duplicates = []; + this.usedDuplicates = null; +} - if (_toString.call(pair) !== '[object Object]') return false; +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; } - if (!pairHasKey) return false; + if (line.length && line !== '\n') result += ind; - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; + result += line; } - return true; + return result; } -function constructYamlOmap(data) { - return data !== null ? data : []; +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); } -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - - -/***/ }), - -/***/ 76039: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -var _toString = Object.prototype.toString; - -function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); +function testImplicitResolving(state, str) { + var index, length, type; - if (keys.length !== 1) return false; + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; - result[index] = [ keys[0], pair[keys[0]] ]; + if (type.resolve(str)) { + return true; + } } - return true; + return false; } -function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} - result = new Array(object.length); +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} - keys = Object.keys(pair); +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} - result[index] = [ keys[0], pair[keys[0]] ]; - } +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} - return result; +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); } -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); -/***/ }), + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} -/***/ 5490: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } -"use strict"; + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } -var Type = __nccwpck_require__(30967); + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); -/***/ }), + return indentIndicator + chomp + '\n'; +} -/***/ 69237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} -"use strict"; +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; -var Type = __nccwpck_require__(30967); + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } -var _hasOwnProperty = Object.prototype.hasOwnProperty; + return result; +} -function resolveYamlSet(data) { - if (data === null) return true; +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; - var key, object = data; + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 } + curr = next; } - return true; -} + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } -function constructYamlSet(data) { - return data !== null ? data : {}; + return result.slice(1); // drop extra \n joiner } -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); - +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; -/***/ }), + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } -/***/ 52672: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return result; +} -"use strict"; +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } -var Type = __nccwpck_require__(30967); + state.tag = _tag; + state.dump = '[' + _result + ']'; +} -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } -/***/ }), + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } -/***/ 83714: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _result += state.dump; + } + } -"use strict"; + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; -var Type = __nccwpck_require__(30967); + for (index = 0, length = objectKeyList.length; index < length; index += 1) { -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + if (state.condenseFlow) pairBuffer += '"'; -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + if (state.dump.length > 1024) pairBuffer += '? '; - if (match === null) throw new Error('Date resolve error'); + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - // match: [1] year [2] month [3] day + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); + pairBuffer += state.dump; - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); + // Both key and value are valid. + _result += pairBuffer; } - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } + state.tag = _tag; + state.dump = '{' + _result + '}'; +} - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); } - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; -} + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } -/***/ }), + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); -/***/ 55586: -/***/ ((module) => { + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } -"use strict"; + pairBuffer += state.dump; + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - if (typeof txt !== 'string') { - const isEmptyArray = Array.isArray(txt) && txt.length === 0 - const errorMessage = 'Cannot parse ' + - (isEmptyArray ? 'an empty array' : String(txt)) - throw new TypeError(errorMessage) + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. } - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` + pairBuffer += ': '; } - throw e + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. } +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; -/***/ }), + typeList = explicit ? state.explicitTypes : state.implicitTypes; -/***/ 53359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; -var jws = __nccwpck_require__(4636); + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { -module.exports = function (jwt, options) { - options = options || {}; - var decoded = jws.decode(jwt, options); - if (!decoded) { return null; } - var payload = decoded.payload; + state.tag = explicit ? type.tag : '?'; - //try parse the payload - if(typeof payload === 'string') { - try { - var obj = JSON.parse(payload); - if(obj !== null && typeof obj === 'object') { - payload = obj; + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; } - } catch (e) { } - } - //return header if `complete` option is enabled. header includes claims - //such as `kid` and `alg` used to select the key within a JWKS needed to - //verify the signature - if (options.complete === true) { - return { - header: decoded.header, - payload: payload, - signature: decoded.signature - }; + return true; + } } - return payload; -}; + return false; +} -/***/ }), - -/***/ 77486: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; -module.exports = { - decode: __nccwpck_require__(53359), - verify: __nccwpck_require__(12327), - sign: __nccwpck_require__(82022), - JsonWebTokenError: __nccwpck_require__(405), - NotBeforeError: __nccwpck_require__(4383), - TokenExpiredError: __nccwpck_require__(46637), -}; + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + var type = _toString.call(state.dump); -/***/ }), + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } -/***/ 405: -/***/ ((module) => { + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; -var JsonWebTokenError = function (message, error) { - Error.call(this, message); - if(Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; } - this.name = 'JsonWebTokenError'; - this.message = message; - if (error) this.inner = error; -}; -JsonWebTokenError.prototype = Object.create(Error.prototype); -JsonWebTokenError.prototype.constructor = JsonWebTokenError; - -module.exports = JsonWebTokenError; + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } -/***/ }), + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } -/***/ 4383: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return true; +} -var JsonWebTokenError = __nccwpck_require__(405); +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; -var NotBeforeError = function (message, date) { - JsonWebTokenError.call(this, message); - this.name = 'NotBeforeError'; - this.date = date; -}; + inspectNode(object, objects, duplicatesIndexes); -NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} -NotBeforeError.prototype.constructor = NotBeforeError; +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; -module.exports = NotBeforeError; + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); -/***/ }), + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); -/***/ 46637: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} -var JsonWebTokenError = __nccwpck_require__(405); +function dump(input, options) { + options = options || {}; -var TokenExpiredError = function (message, expiredAt) { - JsonWebTokenError.call(this, message); - this.name = 'TokenExpiredError'; - this.expiredAt = expiredAt; -}; + var state = new State(options); -TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + if (!state.noRefs) getDuplicateReferences(input, state); -TokenExpiredError.prototype.constructor = TokenExpiredError; + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; -module.exports = TokenExpiredError; + return ''; +} -/***/ }), +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} -/***/ 59085: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports.dump = dump; +module.exports.safeDump = safeDump; -var semver = __nccwpck_require__(27174); -module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); +/***/ }), +/***/ 65199: +/***/ ((module) => { -/***/ }), +"use strict"; +// YAML error class. http://stackoverflow.com/questions/8458984 +// -/***/ 46098: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var ms = __nccwpck_require__(80900); +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); -module.exports = function (time, iat) { - var timestamp = iat || Math.floor(Date.now() / 1000); + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); - if (typeof time === 'string') { - var milliseconds = ms(time); - if (typeof milliseconds === 'undefined') { - return; - } - return Math.floor(timestamp + milliseconds / 1000); - } else if (typeof time === 'number') { - return timestamp + time; + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); } else { - return; + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; } +} -}; -/***/ }), +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; -/***/ 27174: -/***/ ((module, exports) => { -exports = module.exports = SemVer +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); } -} else { - debug = function () {} -} -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' + return result; +}; -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 +module.exports = YAMLException; -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. +/***/ }), -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. +/***/ 45190: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' +"use strict"; -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' +/*eslint-disable max-len,no-use-before-define*/ -// ## Main Version -// Three dot-separated numeric identifiers. +var common = __nccwpck_require__(59136); +var YAMLException = __nccwpck_require__(65199); +var Mark = __nccwpck_require__(55426); +var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); +var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' +var _hasOwnProperty = Object.prototype.hasOwnProperty; -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' +function _class(obj) { return Object.prototype.toString.call(obj); } -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' +function fromHexCode(c) { + var lc; -src[FULL] = '^' + FULLPLAIN + '$' + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' + /*eslint-disable no-bitwise*/ + lc = c | 0x20; -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' + return -1; +} -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' + return -1; +} -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' +function State(input, options) { + this.input = input; -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + this.documents = []; -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' +} -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' +function throwError(state, message) { + throw generateError(state, message); +} -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); } } -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - return version - } +var directiveHandlers = { - if (typeof version !== 'string') { - return null - } + YAML: function handleYamlDirective(state, name, args) { - if (version.length > MAX_LENGTH) { - return null - } + var match, major, minor; - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } -exports.SemVer = SemVer + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } + }, - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } + TAG: function handleTagDirective(state, name, args) { - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } + var handle, prefix; - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + handle = args[0]; + prefix = args[1]; - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } - this.raw = version + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') + state.tagMap[handle] = prefix; } +}; - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); } } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') + state.result += _result; } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version } -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return this.compareMain(other) || this.comparePre(other) -} +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + sourceKeys = Object.keys(source); - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; } - } while (++i) + } } -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); } - break - default: - throw new Error('invalid increment argument: ' + release) + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } } - this.format() - this.raw = this.version - return this -} -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; } - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; } -} -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); } - return defaultResult // may be undefined + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; } + + return _result; } -exports.compareIdentifiers = compareIdentifiers +function readLineBreak(state) { + var ch; -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) + ch = state.input.charCodeAt(state.position); - if (anum && bnum) { - a = +a - b = +b + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 + state.line += 1; + state.lineStart = state.position; } -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} + if (is_EOL(ch)) { + readLineBreak(state); -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) + return lineBreaks; } -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} +function testDocumentSeparator(state) { + var _position = state.position, + ch; -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} + ch = state.input.charCodeAt(_position); -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} + _position += 3; -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} + ch = state.input.charCodeAt(_position); -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 + return false; } -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} - case '>=': - return gte(a, b, loose) - case '<': - return lt(a, b, loose) +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; - case '<=': - return lte(a, b, loose) + ch = state.input.charCodeAt(state.position); - default: - throw new TypeError('Invalid operator: ' + op) + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; } -} -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; } } - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } - debug('comp', this) -} + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) + if (is_WS_OR_EOL(preceding)) { + break; + } - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } -Comparator.prototype.toString = function () { - return this.value -} + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } - if (this.semver === ANY) { - return true + ch = state.input.charCodeAt(++state.position); } - if (typeof version === 'string') { - version = new SemVer(version, this.options) + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; } - return cmp(version, this.operator, this.semver, this.options) + state.kind = _kind; + state.result = _result; + return false; } -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; } - var rangeTmp + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range } else { - return new Range(range.raw, options) + state.position++; + captureEnd = state.position; } } - if (range instanceof Comparator) { - return new Range(range.value, options) - } + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} - if (!(this instanceof Range)) { - return new Range(range, options) +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; } - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; - this.format() -} + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; -Range.prototype.toString = function () { - return this.range -} + } else { + throwError(state, 'expected hexadecimal character'); + } + } -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) + state.result += charFromCodepoint(hexResult); - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) + state.position++; - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) + } else { + throwError(state, 'unknown escape sequence'); + } - // normalize spaces - range = range.split(/\s+/).join(' ') + captureStart = captureEnd = state.position; - // At this point, the range is completely trimmed and - // ready to be split into comparators. + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - return set + throwError(state, 'unexpected end of the stream within a double quoted scalar'); } -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} + ch = state.input.charCodeAt(state.position); -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} + ch = state.input.charCodeAt(++state.position); -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret + ch = state.input.charCodeAt(state.position); - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); } - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); } } - debug('caret return', ret) - return ret - }) -} + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} + ch = state.input.charCodeAt(state.position); -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } - if (gtlt === '=' && anyX) { - gtlt = '' + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); } - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 + skipSeparationSpace(state, true, nodeIndent); - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } + ch = state.input.charCodeAt(state.position); - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; } + } - debug('xRange return', ret) - - return ret - }) + throwError(state, 'unexpected end of the stream within a flow collection'); } -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } + ch = state.input.charCodeAt(state.position); - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; } else { - to = '<=' + to + return false; } - return (from + ' ' + to).trim() -} + state.kind = 'scalar'; + state.result = ''; -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + } else { + break; } } - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); } - - // Version has a -pre, but it's not one of the ones we like. - return false } - return true -} + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} + ch = state.input.charCodeAt(state.position); -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - }) - return max -} -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } } + + // Break this `while` cycle and go to the funciton's epilogue. + break; } - }) - return min -} -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) + // Folded style: use fancy rules to handle line breaks. + if (folding) { - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); } - }) - } - if (minver && range.test(minver)) { - return minver - } + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } - return null -} + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} + captureSegment(state, captureStart, state.position, false); + } -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) + return true; } -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; } - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } + ch = state.input.charCodeAt(state.position); - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + while (ch !== 0) { - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + if (ch !== 0x2D/* - */) { + break; + } - var high = null - var low = null + following = state.input.charCodeAt(state.position + 1); - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) + if (!is_WS_OR_EOL(following)) { + break; + } - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } } - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; } } - return true -} -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; } -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; } - if (typeof version !== 'string') { - return null - } + ch = state.input.charCodeAt(state.position); - var match = version.match(re[COERCE]) + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; - if (match == null) { - return null - } + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) -} + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + detected = true; + atExplicitKey = true; + allowCompact = true; -/***/ }), + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; -/***/ 82022: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } -var timespan = __nccwpck_require__(46098); -var PS_SUPPORTED = __nccwpck_require__(59085); -var jws = __nccwpck_require__(4636); -var includes = __nccwpck_require__(17931); -var isBoolean = __nccwpck_require__(16501); -var isInteger = __nccwpck_require__(21441); -var isNumber = __nccwpck_require__(40298); -var isPlainObject = __nccwpck_require__(25723); -var isString = __nccwpck_require__(25180); -var once = __nccwpck_require__(94499); + state.position += 1; + ch = following; -var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] -if (PS_SUPPORTED) { - SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); -} + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { -var sign_options_schema = { - expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, - notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, - audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, - algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, - header: { isValid: isPlainObject, message: '"header" must be an object' }, - encoding: { isValid: isString, message: '"encoding" must be a string' }, - issuer: { isValid: isString, message: '"issuer" must be a string' }, - subject: { isValid: isString, message: '"subject" must be a string' }, - jwtid: { isValid: isString, message: '"jwtid" must be a string' }, - noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, - keyid: { isValid: isString, message: '"keyid" must be a string' }, - mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } -}; + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); -var registered_claims_schema = { - iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, - exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, - nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } -}; + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } -function validate(schema, allowUnknown, object, parameterName) { - if (!isPlainObject(object)) { - throw new Error('Expected "' + parameterName + '" to be a plain object.'); - } - Object.keys(object) - .forEach(function(key) { - var validator = schema[key]; - if (!validator) { - if (!allowUnknown) { - throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. } - return; - } - if (!validator.isValid(object[key])) { - throw new Error(validator.message); + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. } - }); -} -function validateOptions(options) { - return validate(sign_options_schema, false, options, 'options'); -} + } else { + break; // Reading is done. Go to the epilogue. + } -function validatePayload(payload) { - return validate(registered_claims_schema, true, payload, 'payload'); -} + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } -var options_to_payload = { - 'audience': 'aud', - 'issuer': 'iss', - 'subject': 'sub', - 'jwtid': 'jti' -}; + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } -var options_for_objects = [ - 'expiresIn', - 'notBefore', - 'noTimestamp', - 'audience', - 'issuer', - 'subject', - 'jwtid', -]; + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } -module.exports = function (payload, secretOrPrivateKey, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } else { - options = options || {}; + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } } - var isObjectPayload = typeof payload === 'object' && - !Buffer.isBuffer(payload); - - var header = Object.assign({ - alg: options.algorithm || 'HS256', - typ: isObjectPayload ? 'JWT' : undefined, - kid: options.keyid - }, options.header); + // + // Epilogue. + // - function failure(err) { - if (callback) { - return callback(err); - } - throw err; + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); } - if (!secretOrPrivateKey && options.algorithm !== 'none') { - return failure(new Error('secretOrPrivateKey must have a value')); + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; } - if (typeof payload === 'undefined') { - return failure(new Error('payload is required')); - } else if (isObjectPayload) { - try { - validatePayload(payload); - } - catch (error) { - return failure(error); - } - if (!options.mutatePayload) { - payload = Object.assign({},payload); - } - } else { - var invalid_options = options_for_objects.filter(function (opt) { - return typeof options[opt] !== 'undefined'; - }); + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; - if (invalid_options.length > 0) { - return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); - } - } + ch = state.input.charCodeAt(state.position); - if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { - return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); - } + if (ch !== 0x21/* ! */) return false; - if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { - return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); } - try { - validateOptions(options); - } - catch (error) { - return failure(error); - } + ch = state.input.charCodeAt(++state.position); - var timestamp = payload.iat || Math.floor(Date.now() / 1000); + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); - if (options.noTimestamp) { - delete payload.iat; - } else if (isObjectPayload) { - payload.iat = timestamp; + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; } - if (typeof options.notBefore !== 'undefined') { - try { - payload.nbf = timespan(options.notBefore, timestamp); + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); } - catch (err) { - return failure(err); + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); } - if (typeof payload.nbf === 'undefined') { - return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); } } - if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { - try { - payload.exp = timespan(options.expiresIn, timestamp); - } - catch (err) { - return failure(err); - } - if (typeof payload.exp === 'undefined') { - return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); } - Object.keys(options_to_payload).forEach(function (key) { - var claim = options_to_payload[key]; - if (typeof options[key] !== 'undefined') { - if (typeof payload[claim] !== 'undefined') { - return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); - } - payload[claim] = options[key]; - } - }); + if (isVerbatim) { + state.tag = tagName; - var encoding = options.encoding || 'utf8'; + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; - if (typeof callback === 'function') { - callback = callback && once(callback); + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; - jws.createSign({ - header: header, - privateKey: secretOrPrivateKey, - payload: payload, - encoding: encoding - }).once('error', callback) - .once('done', function (signature) { - callback(null, signature); - }); } else { - return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } -}; + return true; +} -/***/ }), +function readAnchorProperty(state) { + var _position, + ch; -/***/ 12327: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ch = state.input.charCodeAt(state.position); -var JsonWebTokenError = __nccwpck_require__(405); -var NotBeforeError = __nccwpck_require__(4383); -var TokenExpiredError = __nccwpck_require__(46637); -var decode = __nccwpck_require__(53359); -var timespan = __nccwpck_require__(46098); -var PS_SUPPORTED = __nccwpck_require__(59085); -var jws = __nccwpck_require__(4636); + if (ch !== 0x26/* & */) return false; -var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; -var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; -var HS_ALGS = ['HS256', 'HS384', 'HS512']; + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } -if (PS_SUPPORTED) { - PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); - RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); -} + ch = state.input.charCodeAt(++state.position); + _position = state.position; -module.exports = function (jwtString, secretOrPublicKey, options, callback) { - if ((typeof options === 'function') && !callback) { - callback = options; - options = {}; + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } - if (!options) { - options = {}; + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); } - //clone this object since we are going to mutate it. - options = Object.assign({}, options); - - var done; + state.anchor = state.input.slice(_position, state.position); + return true; +} - if (callback) { - done = callback; - } else { - done = function(err, data) { - if (err) throw err; - return data; - }; - } +function readAlias(state) { + var _position, alias, + ch; - if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { - return done(new JsonWebTokenError('clockTimestamp must be a number')); - } + ch = state.input.charCodeAt(state.position); - if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { - return done(new JsonWebTokenError('nonce must be a non-empty string')); - } + if (ch !== 0x2A/* * */) return false; - var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); + ch = state.input.charCodeAt(++state.position); + _position = state.position; - if (!jwtString){ - return done(new JsonWebTokenError('jwt must be provided')); + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } - if (typeof jwtString !== 'string') { - return done(new JsonWebTokenError('jwt must be a string')); + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); } - var parts = jwtString.split('.'); + alias = state.input.slice(_position, state.position); - if (parts.length !== 3){ - return done(new JsonWebTokenError('jwt malformed')); + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); } - var decodedToken; + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} - try { - decodedToken = decode(jwtString, { complete: true }); - } catch(err) { - return done(err); - } +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } } + } - var hasSignature = parts[2].trim() !== ''; + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; - if (!hasSignature && secretOrPublicKey){ - return done(new JsonWebTokenError('jwt signature is required')); + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } } + } - if (hasSignature && !secretOrPublicKey) { - return done(new JsonWebTokenError('secret or public key must be provided')); - } + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } - if (!hasSignature && !options.algorithms) { - options.algorithms = ['none']; + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; } - if (!options.algorithms) { - options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || - ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : - ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; - - } + blockIndent = state.position - state.lineStart; - if (!~options.algorithms.indexOf(decodedToken.header.alg)) { - return done(new JsonWebTokenError('invalid algorithm')); - } + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; - var valid; + } else if (readAlias(state)) { + hasContent = true; - try { - valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); - } catch (e) { - return done(e); - } + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } - if (!valid) { - return done(new JsonWebTokenError('invalid signature')); - } + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; - var payload = decodedToken.payload; + if (state.tag === null) { + state.tag = '?'; + } + } - if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { - if (typeof payload.nbf !== 'number') { - return done(new JsonWebTokenError('invalid nbf value')); - } - if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { - return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } + } - if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { - if (typeof payload.exp !== 'number') { - return done(new JsonWebTokenError('invalid exp value')); - } - if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } - } - - if (options.audience) { - var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; - var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; - var match = target.some(function (targetAudience) { - return audiences.some(function (audience) { - return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; - }); - }); + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; - if (!match) { - return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } } - } - - if (options.issuer) { - var invalid_issuer = - (typeof options.issuer === 'string' && payload.iss !== options.issuer) || - (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; - if (invalid_issuer) { - return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } - } - if (options.subject) { - if (payload.sub !== options.subject) { - return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); } + } - if (options.jwtid) { - if (payload.jti !== options.jwtid) { - return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); - } - } + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} - if (options.nonce) { - if (payload.nonce !== options.nonce) { - return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); - } +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; } - if (options.maxAge) { - if (typeof payload.iat !== 'number') { - return done(new JsonWebTokenError('iat required when maxAge is specified')); - } + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; - var maxAgeTimestamp = timespan(options.maxAge, payload.iat); - if (typeof maxAgeTimestamp === 'undefined') { - return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); - } + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); } - if (options.complete === true) { - var signature = decodedToken.signature; + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; - return done(null, { - header: header, - payload: payload, - signature: signature - }); + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); } - return done(null, payload); - }); -}; + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } -/***/ }), + if (is_EOL(ch)) break; -/***/ 96010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _position = state.position; -var bufferEqual = __nccwpck_require__(9239); -var Buffer = __nccwpck_require__(21867).Buffer; -var crypto = __nccwpck_require__(76417); -var formatEcdsa = __nccwpck_require__(11728); -var util = __nccwpck_require__(31669); + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } -var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' -var MSG_INVALID_SECRET = 'secret must be a string or buffer'; -var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; -var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + directiveArgs.push(state.input.slice(_position, state.position)); + } -var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; -if (supportsKeyObjects) { - MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; - MSG_INVALID_SECRET += 'or a KeyObject'; -} + if (ch !== 0) readLineBreak(state); -function checkIsPublicKey(key) { - if (Buffer.isBuffer(key)) { - return; + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } } - if (typeof key === 'string') { - return; - } + skipSeparationSpace(state, true, -1); - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_VERIFIER_KEY); + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); } - if (typeof key.type !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); - if (typeof key.asymmetricKeyType !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } -}; + state.documents.push(state.result); -function checkIsPrivateKey(key) { - if (Buffer.isBuffer(key)) { - return; - } + if (state.position === state.lineStart && testDocumentSeparator(state)) { - if (typeof key === 'string') { + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } return; } - if (typeof key === 'object') { + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { return; } +} - throw typeError(MSG_INVALID_SIGNER_KEY); -}; -function checkIsSecretKey(key) { - if (Buffer.isBuffer(key)) { - return; - } +function loadDocuments(input, options) { + input = String(input); + options = options || {}; - if (typeof key === 'string') { - return key; - } + if (input.length !== 0) { - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_SECRET); - } + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_SECRET); + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } } - if (key.type !== 'secret') { - throw typeError(MSG_INVALID_SECRET); - } + var state = new State(input, options); - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_SECRET); + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); } -} -function fromBase64(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; -function toBase64(base64url) { - base64url = base64url.toString(); + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } - var padding = 4 - base64url.length % 4; - if (padding !== 4) { - for (var i = 0; i < padding; ++i) { - base64url += '='; - } + while (state.position < (state.length - 1)) { + readDocument(state); } - return base64url - .replace(/\-/g, '+') - .replace(/_/g, '/'); + return state.documents; } -function typeError(template) { - var args = [].slice.call(arguments, 1); - var errMsg = util.format.bind(util, template).apply(null, args); - return new TypeError(errMsg); -} -function bufferOrString(obj) { - return Buffer.isBuffer(obj) || typeof obj === 'string'; -} +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } -function normalizeInput(thing) { - if (!bufferOrString(thing)) - thing = JSON.stringify(thing); - return thing; -} + var documents = loadDocuments(input, options); -function createHmacSigner(bits) { - return function sign(thing, secret) { - checkIsSecretKey(secret); - thing = normalizeInput(thing); - var hmac = crypto.createHmac('sha' + bits, secret); - var sig = (hmac.update(thing), hmac.digest('base64')) - return fromBase64(sig); + if (typeof iterator !== 'function') { + return documents; } -} -function createHmacVerifier(bits) { - return function verify(thing, signature, secret) { - var computedSig = createHmacSigner(bits)(thing, secret); - return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); } } -function createKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - // Even though we are specifying "RSA" here, this works with ECDSA - // keys as well. - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); - return fromBase64(sig); - } -} -function createKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify(publicKey, signature, 'base64'); - } -} +function load(input, options) { + var documents = loadDocuments(input, options); -function createPSSKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign({ - key: privateKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, 'base64')); - return fromBase64(sig); + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; } + throw new YAMLException('expected a single document in the stream, but found more'); } -function createPSSKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify({ - key: publicKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, signature, 'base64'); - } -} -function createECDSASigner(bits) { - var inner = createKeySigner(bits); - return function sign() { - var signature = inner.apply(null, arguments); - signature = formatEcdsa.derToJose(signature, 'ES' + bits); - return signature; - }; -} +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } -function createECDSAVerifer(bits) { - var inner = createKeyVerifier(bits); - return function verify(thing, signature, publicKey) { - signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); - var result = inner(thing, signature, publicKey); - return result; - }; + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); } -function createNoneSigner() { - return function sign() { - return ''; - } -} -function createNoneVerifier() { - return function verify(thing, signature) { - return signature === ''; - } +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); } -module.exports = function jwa(algorithm) { - var signerFactories = { - hs: createHmacSigner, - rs: createKeySigner, - ps: createPSSKeySigner, - es: createECDSASigner, - none: createNoneSigner, - } - var verifierFactories = { - hs: createHmacVerifier, - rs: createKeyVerifier, - ps: createPSSKeyVerifier, - es: createECDSAVerifer, - none: createNoneVerifier, - } - var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); - if (!match) - throw typeError(MSG_INVALID_ALGORITHM, algorithm); - var algo = (match[1] || match[3]).toLowerCase(); - var bits = match[2]; - return { - sign: signerFactories[algo](bits), - verify: verifierFactories[algo](bits), - } -}; +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; /***/ }), -/***/ 4636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 55426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global exports*/ -var SignStream = __nccwpck_require__(73334); -var VerifyStream = __nccwpck_require__(5522); +"use strict"; -var ALGORITHMS = [ - 'HS256', 'HS384', 'HS512', - 'RS256', 'RS384', 'RS512', - 'PS256', 'PS384', 'PS512', - 'ES256', 'ES384', 'ES512' -]; -exports.ALGORITHMS = ALGORITHMS; -exports.sign = SignStream.sign; -exports.verify = VerifyStream.verify; -exports.decode = VerifyStream.decode; -exports.isValid = VerifyStream.isValid; -exports.createSign = function createSign(opts) { - return new SignStream(opts); -}; -exports.createVerify = function createVerify(opts) { - return new VerifyStream(opts); -}; +var common = __nccwpck_require__(59136); -/***/ }), -/***/ 61868: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} -/*global module, process*/ -var Buffer = __nccwpck_require__(21867).Buffer; -var Stream = __nccwpck_require__(92413); -var util = __nccwpck_require__(31669); -function DataStream(data) { - this.buffer = null; - this.writable = true; - this.readable = true; +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; - // No input - if (!data) { - this.buffer = Buffer.alloc(0); - return this; - } + if (!this.buffer) return null; - // Stream - if (typeof data.pipe === 'function') { - this.buffer = Buffer.alloc(0); - data.pipe(this); - return this; + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } } - // Buffer or String - // or Object (assumedly a passworded key) - if (data.length || typeof data === 'object') { - this.buffer = data; - this.writable = false; - process.nextTick(function () { - this.emit('end', data); - this.readable = false; - this.emit('close'); - }.bind(this)); - return this; + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } } - throw new TypeError('Unexpected data type ('+ typeof data + ')'); -} -util.inherits(DataStream, Stream); + snippet = this.buffer.slice(start, end); -DataStream.prototype.write = function write(data) { - this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); - this.emit('data', data); + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; }; -DataStream.prototype.end = function end(data) { - if (data) - this.write(data); - this.emit('end', data); - this.emit('close'); - this.writable = false; - this.readable = false; -}; -module.exports = DataStream; +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + if (this.name) { + where += 'in "' + this.name + '" '; + } -/***/ }), + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); -/***/ 73334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!compact) { + snippet = this.getSnippet(); -/*global module*/ -var Buffer = __nccwpck_require__(21867).Buffer; -var DataStream = __nccwpck_require__(61868); -var jwa = __nccwpck_require__(96010); -var Stream = __nccwpck_require__(92413); -var toString = __nccwpck_require__(65292); -var util = __nccwpck_require__(31669); + if (snippet) { + where += ':\n' + snippet; + } + } -function base64url(string, encoding) { - return Buffer - .from(string, encoding) - .toString('base64') - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} + return where; +}; -function jwsSecuredInput(header, payload, encoding) { - encoding = encoding || 'utf8'; - var encodedHeader = base64url(toString(header), 'binary'); - var encodedPayload = base64url(toString(payload), encoding); - return util.format('%s.%s', encodedHeader, encodedPayload); -} -function jwsSign(opts) { - var header = opts.header; - var payload = opts.payload; - var secretOrKey = opts.secret || opts.privateKey; - var encoding = opts.encoding; - var algo = jwa(header.alg); - var securedInput = jwsSecuredInput(header, payload, encoding); - var signature = algo.sign(securedInput, secretOrKey); - return util.format('%s.%s', securedInput, signature); -} +module.exports = Mark; -function SignStream(opts) { - var secret = opts.secret||opts.privateKey||opts.key; - var secretStream = new DataStream(secret); - this.readable = true; - this.header = opts.header; - this.encoding = opts.encoding; - this.secret = this.privateKey = this.key = secretStream; - this.payload = new DataStream(opts.payload); - this.secret.once('close', function () { - if (!this.payload.writable && this.readable) - this.sign(); - }.bind(this)); - this.payload.once('close', function () { - if (!this.secret.writable && this.readable) - this.sign(); - }.bind(this)); -} -util.inherits(SignStream, Stream); +/***/ }), -SignStream.prototype.sign = function sign() { - try { - var signature = jwsSign({ - header: this.header, - payload: this.payload.buffer, - secret: this.secret.buffer, - encoding: this.encoding - }); - this.emit('done', signature); - this.emit('data', signature); - this.emit('end'); - this.readable = false; - return signature; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; +/***/ 66514: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -SignStream.sign = jwsSign; +"use strict"; -module.exports = SignStream; +/*eslint-disable max-len*/ -/***/ }), +var common = __nccwpck_require__(59136); +var YAMLException = __nccwpck_require__(65199); +var Type = __nccwpck_require__(30967); -/***/ 65292: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global module*/ -var Buffer = __nccwpck_require__(64293).Buffer; +function compileList(schema, name, result) { + var exclude = []; -module.exports = function toString(obj) { - if (typeof obj === 'string') - return obj; - if (typeof obj === 'number' || Buffer.isBuffer(obj)) - return obj.toString(); - return JSON.stringify(obj); -}; + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + result.push(currentType); + }); -/***/ }), + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} -/***/ 5522: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global module*/ -var Buffer = __nccwpck_require__(21867).Buffer; -var DataStream = __nccwpck_require__(61868); -var jwa = __nccwpck_require__(96010); -var Stream = __nccwpck_require__(92413); -var toString = __nccwpck_require__(65292); -var util = __nccwpck_require__(31669); -var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; -function isObject(thing) { - return Object.prototype.toString.call(thing) === '[object Object]'; -} + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } -function safeJsonParse(thing) { - if (isObject(thing)) - return thing; - try { return JSON.parse(thing); } - catch (e) { return undefined; } + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; } -function headerFromJWS(jwsSig) { - var encodedHeader = jwsSig.split('.', 1)[0]; - return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); -} -function securedInputFromJWS(jwsSig) { - return jwsSig.split('.', 2).join('.'); -} +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; -function signatureFromJWS(jwsSig) { - return jwsSig.split('.')[2]; -} + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); -function payloadFromJWS(jwsSig, encoding) { - encoding = encoding || 'utf8'; - var payload = jwsSig.split('.')[1]; - return Buffer.from(payload, 'base64').toString(encoding); + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); } -function isValidJws(string) { - return JWS_REGEX.test(string) && !!headerFromJWS(string); -} -function jwsVerify(jwsSig, algorithm, secretOrKey) { - if (!algorithm) { - var err = new Error("Missing algorithm parameter for jws.verify"); - err.code = "MISSING_ALGORITHM"; - throw err; - } - jwsSig = toString(jwsSig); - var signature = signatureFromJWS(jwsSig); - var securedInput = securedInputFromJWS(jwsSig); - var algo = jwa(algorithm); - return algo.verify(securedInput, signature, secretOrKey); -} +Schema.DEFAULT = null; -function jwsDecode(jwsSig, opts) { - opts = opts || {}; - jwsSig = toString(jwsSig); - if (!isValidJws(jwsSig)) - return null; +Schema.create = function createSchema() { + var schemas, types; - var header = headerFromJWS(jwsSig); + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; - if (!header) - return null; + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; - var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } - return { - header: header, - payload: payload, - signature: signatureFromJWS(jwsSig) - }; -} + schemas = common.toArray(schemas); + types = common.toArray(types); -function VerifyStream(opts) { - opts = opts || {}; - var secretOrKey = opts.secret||opts.publicKey||opts.key; - var secretStream = new DataStream(secretOrKey); - this.readable = true; - this.algorithm = opts.algorithm; - this.encoding = opts.encoding; - this.secret = this.publicKey = this.key = secretStream; - this.signature = new DataStream(opts.signature); - this.secret.once('close', function () { - if (!this.signature.writable && this.readable) - this.verify(); - }.bind(this)); + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } - this.signature.once('close', function () { - if (!this.secret.writable && this.readable) - this.verify(); - }.bind(this)); -} -util.inherits(VerifyStream, Stream); -VerifyStream.prototype.verify = function verify() { - try { - var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); - var obj = jwsDecode(this.signature.buffer, this.encoding); - this.emit('done', valid, obj); - this.emit('data', valid); - this.emit('end'); - this.readable = false; - return valid; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } + + return new Schema({ + include: schemas, + explicit: types + }); }; -VerifyStream.decode = jwsDecode; -VerifyStream.isValid = isValidJws; -VerifyStream.verify = jwsVerify; -module.exports = VerifyStream; +module.exports = Schema; /***/ }), -/***/ 75978: +/***/ 92183: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. -const path = __nccwpck_require__(85622); -const fs = __nccwpck_require__(18962); -const stripBom = __nccwpck_require__(88551); -const parseJson = __nccwpck_require__(81680); -const pify = __nccwpck_require__(64810); -const parse = (data, filePath, options = {}) => { - data = stripBom(data); - if (typeof options.beforeParse === 'function') { - data = options.beforeParse(data); - } - return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); -}; -const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); +var Schema = __nccwpck_require__(66514); -module.exports = loadJsonFile; -module.exports.default = loadJsonFile; -module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); + +module.exports = new Schema({ + include: [ + __nccwpck_require__(1571) + ] +}); /***/ }), -/***/ 70760: -/***/ ((module) => { +/***/ 56874: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. -module.exports = clone -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) +var Schema = __nccwpck_require__(66514); - return copy -} + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + __nccwpck_require__(48949) + ], + explicit: [ + __nccwpck_require__(25914), + __nccwpck_require__(69242), + __nccwpck_require__(27278) + ] +}); /***/ }), -/***/ 18962: +/***/ 48949: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var fs = __nccwpck_require__(35747) -var polyfills = __nccwpck_require__(11566) -var legacy = __nccwpck_require__(21357) -var clone = __nccwpck_require__(70760) +"use strict"; +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) -var queue = [] -var util = __nccwpck_require__(31669) -function noop () {} -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } -if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(queue) - __nccwpck_require__(42357).equal(queue.length, 0) - }) -} +var Schema = __nccwpck_require__(66514); -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} -// Always patch fs.close/closeSync, because we want to -// retry() whenever a close happens *anywhere* in the program. -// This is essential when multiple graceful-fs instances are -// in play at the same time. -module.exports.close = (function (fs$close) { return function (fd, cb) { - return fs$close.call(fs, fd, function (err) { - if (!err) - retry() +module.exports = new Schema({ + include: [ + __nccwpck_require__(92183) + ], + implicit: [ + __nccwpck_require__(83714), + __nccwpck_require__(81393) + ], + explicit: [ + __nccwpck_require__(32551), + __nccwpck_require__(96668), + __nccwpck_require__(76039), + __nccwpck_require__(69237) + ] +}); - if (typeof cb === 'function') - cb.apply(this, arguments) - }) -}})(fs.close) - -module.exports.closeSync = (function (fs$closeSync) { return function (fd) { - // Note that graceful-fs also retries when fs.closeSync() fails. - // Looks like a bug to me, although it's probably a harmless one. - var rval = fs$closeSync.apply(fs, arguments) - retry() - return rval -}})(fs.closeSync) - -// Only patch fs once, otherwise we'll run into a memory leak if -// graceful-fs is loaded multiple times, such as in test environments that -// reset the loaded modules between tests. -// We look for the string `graceful-fs` from the comment above. This -// way we are not adding any extra properties and it will detect if older -// versions of graceful-fs are installed. -if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) { - fs.closeSync = module.exports.closeSync; - fs.close = module.exports.close; -} -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - fs.FileReadStream = ReadStream; // Legacy name. - fs.FileWriteStream = WriteStream; // Legacy name. - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/***/ }), - return go$readFile(path, options, cb) +/***/ 66037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } +"use strict"; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - return go$writeFile(path, data, options, cb) - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - return go$appendFile(path, data, options, cb) +var Schema = __nccwpck_require__(66514); - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options - } - args.push(go$readdir$cb) +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(52672), + __nccwpck_require__(5490), + __nccwpck_require__(31173) + ] +}); - return go$readdir(args) - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() +/***/ }), - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) +/***/ 1571: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - } - } +"use strict"; +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } - fs.ReadStream = ReadStream - fs.WriteStream = WriteStream +var Schema = __nccwpck_require__(66514); - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() +module.exports = new Schema({ + include: [ + __nccwpck_require__(66037) + ], + implicit: [ + __nccwpck_require__(22671), + __nccwpck_require__(94675), + __nccwpck_require__(89963), + __nccwpck_require__(15564) + ] +}); - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } +/***/ }), - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } +/***/ 30967: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function createReadStream (path, options) { - return new ReadStream(path, options) - } +"use strict"; - function createWriteStream (path, options) { - return new WriteStream(path, options) - } - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null +var YAMLException = __nccwpck_require__(65199); - return go$open(path, flags, mode, cb) +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); } - return fs + return result; } -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - queue.push(elem) -} +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); -function retry () { - var elem = queue.shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } +module.exports = Type; + /***/ }), -/***/ 21357: +/***/ 32551: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Stream = __nccwpck_require__(92413).Stream +"use strict"; -module.exports = legacy -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } +/*eslint-disable no-bitwise*/ - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +var NodeBuffer; - Stream.call(this); +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} - var self = this; +var Type = __nccwpck_require__(30967); - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - options = options || {}; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +function resolveYamlBinary(data) { + if (data === null) return false; - if (this.encoding) this.setEncoding(this.encoding); + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); - if (this.start > this.end) { - throw new Error('start must be <= end'); - } + // Skip CR/LF + if (code > 64) continue; - this.pos = this.start; - } + // Fail on illegal characters + if (code < 0) return false; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } + bitlen += 6; + } - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} - self.fd = fd; - self.emit('open', fd); - self._read(); - }) +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + // Dump tail - Stream.call(this); + tailbits = (max % 4) * 6; - this.path = path; - this.fd = null; - this.writable = true; + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } - options = options || {}; + return result; +} - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + // Convert every three bytes to 4 ASCII characters. - this.pos = this.start; + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; } - this.busy = false; - this._queue = []; + bits = (bits << 8) + object[idx]; + } - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); } +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + /***/ }), -/***/ 11566: +/***/ 94675: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var constants = __nccwpck_require__(27619) +"use strict"; -var origCwd = process.cwd -var cwd = null -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +var Type = __nccwpck_require__(30967); -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } -try { - process.cwd() -} catch (er) {} -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; } -module.exports = patch +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} -function patch (fs) { - // (re-)implement some things that are known busted or missing. +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) + +/***/ }), + +/***/ 15564: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var common = __nccwpck_require__(59136); +var Type = __nccwpck_require__(30967); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; } - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); } - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + } else if (value === '.nan') { + return NaN; - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + value = 0.0; + base = 1; - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + return sign * value; - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + } + return sign * parseFloat(value, 10); +} - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; } - fs.lchownSync = function () {} + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + res = object.toString(10); - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - }})(fs.read) + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +/***/ }), + +/***/ 89963: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var common = __nccwpck_require__(59136); +var Type = __nccwpck_require__(30967); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +function resolveYamlInteger(data) { + if (data === null) return false; - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } + var max = data.length, + index = 0, + hasDigits = false, + ch; - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } + if (!max) return false; - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } + ch = data[index]; - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; } + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } + // base 2, base 8, base 16 - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; } + return hasDigits && ch !== '_'; } - } - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, cb) { - return orig.call(fs, target, function (er, stats) { - if (!stats) return cb.apply(this, arguments) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - if (cb) cb.apply(this, arguments) - }) + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - } - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target) { - var stats = orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; } + return hasDigits && ch !== '_'; } - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true + // base 10 (except 0) or base 60 - if (er.code === "ENOSYS") - return true + // value should not start with `_`; + if (ch === '_') return false; - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; } - - return false + hasDigits = true; } -} - - -/***/ }), -/***/ 81680: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; -"use strict"; + // if !base60 - done; + if (ch !== ':') return true; -const errorEx = __nccwpck_require__(23505); -const fallback = __nccwpck_require__(55586); + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s') -}); +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; -module.exports = (input, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; - } + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } - try { - try { - return JSON.parse(input, reviver); - } catch (err) { - fallback(input, reviver); + ch = value[0]; - throw err; - } - } catch (err) { - err.message = err.message.replace(/\n/g, ''); + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } - const jsonErr = new JSONError(err); - if (filename) { - jsonErr.fileName = filename; - } + if (value === '0') return 0; - throw jsonErr; - } -}; + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); -/***/ }), + value = 0; + base = 1; -/***/ 11289: -/***/ ((module) => { + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + return sign * value; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + } -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + return sign * parseInt(value, 10); +} -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @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]); +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] } - return func.apply(thisArg, args); -} +}); -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} +/***/ }), -/** Used for built-in method references. */ -var objectProto = Object.prototype; +/***/ 27278: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +"use strict"; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; +var esprima; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; +var Type = __nccwpck_require__(30967); - var length = result.length, - skipIndexes = !!length; +function resolveJavascriptFunction(data) { + if (data === null) return false; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; } - } - return result; -} -/** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @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 assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; + return true; + } catch (err) { + return false; } - return objValue; } -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } -} +function constructJavascriptFunction(data) { + /*jslint evil:true*/ -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @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 source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); } - var isProto = isPrototype(object), - result = []; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); } - return result; + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); } -/** - * 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) { - 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); +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; } -/** - * Copies properties of `source` to `object`. - * - * @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) { - object || (object = {}); +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); - 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; +/***/ 69242: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; -} +"use strict"; -/** - * Creates a function like `_.assign`. - * - * @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; +var Type = __nccwpck_require__(30967); - 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; - }); -} +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; -/** - * Checks if `value` is a valid array-like index. - * - * @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); -} + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; -/** - * Checks if the given arguments are from an iteratee call. - * - * @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); + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; } - return false; + + return true; } -/** - * Checks if `value` is likely a prototype object. - * - * @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; +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; - return value === proto; + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); } -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @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); - } - } +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + return result; } -/** - * 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 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 - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; } -/** - * Checks if `value` is likely an `arguments` 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`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); -/** - * Checks if `value` is classified as an `Array` object. - * - * @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 - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; -/** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.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.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} +/***/ 25914: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; +"use strict"; + + +var Type = __nccwpck_require__(30967); + +function resolveJavascriptUndefined() { + return true; } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @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 - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; } -/** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +function representJavascriptUndefined() { + return ''; } -/** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function isUndefined(object) { + return typeof object === 'undefined'; } -/** - * 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 mutates `object`. - * - * @static - * @memberOf _ - * @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 customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * 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); +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined }); -/** - * 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. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @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, assignInDefaults); - return apply(assignInWith, undefined, args); + +/***/ }), + +/***/ 31173: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(30967); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } }); -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * 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); + +/***/ }), + +/***/ 81393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(30967); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; } -module.exports = defaults; +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); /***/ }), -/***/ 48919: -/***/ ((module) => { +/***/ 22671: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +"use strict"; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +var Type = __nccwpck_require__(30967); -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +function resolveYamlNull(data) { + if (data === null) return true; -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + var max = data.length; -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +function constructYamlNull() { + return null; +} - while (++index < length) { - array[offset + index] = values[index]; - } - return array; +function isNull(object) { + return object === null; } -/** Used for built-in method references. */ -var objectProto = Object.prototype; +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +/***/ }), -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; +/***/ 96668: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * 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; +"use strict"; - 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); +var Type = __nccwpck_require__(30967); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; } - } else if (!isStrict) { - result[result.length] = value; } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; } - return result; -} -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @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]); + return true; } -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @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 ? array.length : 0; - return length ? baseFlatten(array, 1) : []; +function constructYamlOmap(data) { + return data !== null ? data : []; } -/** - * Checks if `value` is likely an `arguments` 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`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); -/** - * Checks if `value` is classified as an `Array` object. - * - * @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 - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; -/** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.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.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} +/***/ 76039: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} +"use strict"; -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @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 - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} +var Type = __nccwpck_require__(30967); -/** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} +var _toString = Object.prototype.toString; -module.exports = flatten; +function resolveYamlPairs(data) { + if (data === null) return true; + var index, length, pair, keys, result, + object = data; -/***/ }), + result = new Array(object.length); -/***/ 17931: -/***/ ((module) => { + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + if (_toString.call(pair) !== '[object Object]') return false; -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + keys = Object.keys(pair); -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - stringTag = '[object String]', - symbolTag = '[object Symbol]'; + if (keys.length !== 1) return false; -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; + result[index] = [ keys[0], pair[keys[0]] ]; + } -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + return true; +} -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; +function constructYamlPairs(data) { + if (data === null) return []; -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; + var index, length, pair, keys, result, + object = data; -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; + result = new Array(object.length); -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); + keys = Object.keys(pair); - while (++index < length) { - result[index] = iteratee(array[index], index, array); + result[index] = [ keys[0], pair[keys[0]] ]; } + return result; } -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + + +/***/ }), + +/***/ 5490: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(30967); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + + +/***/ }), + +/***/ 69237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} +var Type = __nccwpck_require__(30967); -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); - } - var index = fromIndex - 1, - length = array.length; +var _hasOwnProperty = Object.prototype.hasOwnProperty; - while (++index < length) { - if (array[index] === value) { - return index; +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; } } - return -1; + + return true; } -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; +function constructYamlSet(data) { + return data !== null ? data : {}; } -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} -/** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ -function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); -} +/***/ }), -/** - * 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)); - }; -} +/***/ 52672: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Used for built-in method references. */ -var objectProto = Object.prototype; +"use strict"; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +var Type = __nccwpck_require__(30967); -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max; -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; +/***/ }), - var length = result.length, - skipIndexes = !!length; +/***/ 83714: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; -} +"use strict"; -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @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; -} -/** - * Checks if `value` is a valid array-like index. - * - * @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); -} +var Type = __nccwpck_require__(30967); -/** - * Checks if `value` is likely a prototype object. - * - * @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; +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day - return value === proto; +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; } -/** - * 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 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 - * - * _.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; +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; - 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); -} + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); -/** - * Checks if `value` is likely an `arguments` 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`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} + if (match === null) throw new Error('Date resolve error'); -/** - * Checks if `value` is classified as an `Array` object. - * - * @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 - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + // match: [1] year [2] month [3] day -/** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @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`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} + // match: [4] hour [5] minute [6] second [7] fraction -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @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 - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); -/** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } -/** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @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 - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @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 - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.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; +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + + +/***/ }), + +/***/ 55586: +/***/ ((module) => { + +"use strict"; + + +module.exports = parseJson +function parseJson (txt, reviver, context) { + context = context || 20 + try { + return JSON.parse(txt, reviver) + } catch (e) { + if (typeof txt !== 'string') { + const isEmptyArray = Array.isArray(txt) && txt.length === 0 + const errorMessage = 'Cannot parse ' + + (isEmptyArray ? 'an empty array' : String(txt)) + throw new TypeError(errorMessage) + } + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'` + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'` + } + throw e } - 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 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.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 a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.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; +/***/ 53359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var jws = __nccwpck_require__(4636); + +module.exports = function (jwt, options) { + options = options || {}; + var decoded = jws.decode(jwt, options); + if (!decoded) { return null; } + var payload = decoded.payload; + + //try parse the payload + if(typeof payload === 'string') { + try { + var obj = JSON.parse(payload); + if(obj !== null && typeof obj === 'object') { + payload = obj; + } + } catch (e) { } } - if (typeof value != 'string') { - return value === 0 ? value : +value; + + //return header if `complete` option is enabled. header includes claims + //such as `kid` and `alg` used to select the key within a JWKS needed to + //verify the signature + if (options.complete === true) { + return { + header: decoded.header, + payload: payload, + signature: decoded.signature + }; } - 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); -} + return payload; +}; -/** - * Creates an array of the own enumerable property names of `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 _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} -/** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ -function values(object) { - return object ? baseValues(object, keys(object)) : []; -} +/***/ }), -module.exports = includes; +/***/ 77486: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = { + decode: __nccwpck_require__(53359), + verify: __nccwpck_require__(12327), + sign: __nccwpck_require__(82022), + JsonWebTokenError: __nccwpck_require__(405), + NotBeforeError: __nccwpck_require__(4383), + TokenExpiredError: __nccwpck_require__(46637), +}; /***/ }), -/***/ 16501: +/***/ 405: /***/ ((module) => { -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ +var JsonWebTokenError = function (message, error) { + Error.call(this, message); + if(Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = 'JsonWebTokenError'; + this.message = message; + if (error) this.inner = error; +}; -/** `Object#toString` result references. */ -var boolTag = '[object Boolean]'; +JsonWebTokenError.prototype = Object.create(Error.prototype); +JsonWebTokenError.prototype.constructor = JsonWebTokenError; -/** Used for built-in method references. */ -var objectProto = Object.prototype; +module.exports = JsonWebTokenError; -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; -/** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ -function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && objectToString.call(value) == boolTag); -} +/***/ }), -/** - * 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 _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +/***/ 4383: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var JsonWebTokenError = __nccwpck_require__(405); + +var NotBeforeError = function (message, date) { + JsonWebTokenError.call(this, message); + this.name = 'NotBeforeError'; + this.date = date; +}; + +NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); + +NotBeforeError.prototype.constructor = NotBeforeError; + +module.exports = NotBeforeError; + +/***/ }), + +/***/ 46637: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var JsonWebTokenError = __nccwpck_require__(405); + +var TokenExpiredError = function (message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = 'TokenExpiredError'; + this.expiredAt = expiredAt; +}; + +TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + +TokenExpiredError.prototype.constructor = TokenExpiredError; + +module.exports = TokenExpiredError; + +/***/ }), + +/***/ 59085: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var semver = __nccwpck_require__(27174); + +module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); + + +/***/ }), + +/***/ 46098: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var ms = __nccwpck_require__(80900); + +module.exports = function (time, iat) { + var timestamp = iat || Math.floor(Date.now() / 1000); + + if (typeof time === 'string') { + var milliseconds = ms(time); + if (typeof milliseconds === 'undefined') { + return; + } + return Math.floor(timestamp + milliseconds / 1000); + } else if (typeof time === 'number') { + return timestamp + time; + } else { + return; + } + +}; + +/***/ }), + +/***/ 27174: +/***/ ((module, exports) => { + +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} } -module.exports = isBoolean; +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' -/***/ }), +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' -/***/ 21441: -/***/ ((module) => { +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. -/** Used for built-in method references. */ -var objectProto = Object.prototype; +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. -/** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @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`. - * @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); -} +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. -/** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' -/** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} +src[FULL] = '^' + FULLPLAIN + '$' -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @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 - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.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; -} +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' -/** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.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; +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' - return result === result ? (remainder ? result - remainder : result) : 0; -} +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.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); -} +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' -module.exports = isInteger; +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' -/***/ }), +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' -/***/ 40298: -/***/ ((module) => { +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' -/** `Object#toString` result references. */ -var numberTag = '[object Number]'; +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' -/** Used for built-in method references. */ -var objectProto = Object.prototype; +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' -/** - * 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 _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' -/** - * 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 _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ -function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && objectToString.call(value) == numberTag); -} +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' -module.exports = isNumber; +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' -/***/ }), +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' -/***/ 25723: -/***/ ((module) => { +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + try { + return new SemVer(version, options) + } catch (er) { + return null } - 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)); - }; +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null } -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; +exports.SemVer = SemVer -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString.call(Object); + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose -/** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) -/** - * 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 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || - objectToString.call(value) != objectTag || isHostObject(value)) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; + if (!m) { + throw new TypeError('Invalid Version: ' + version) } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} -module.exports = isPlainObject; + this.raw = version + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] -/***/ }), + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -/***/ 25180: -/***/ ((module) => { + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } -/** - * lodash 4.0.1 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } -/** `Object#toString` result references. */ -var stringTag = '[object String]'; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } -/** Used for built-in method references. */ -var objectProto = Object.prototype; + this.build = m[5] ? m[5].split('.') : [] + this.format() +} -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @type Function - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +SemVer.prototype.toString = function () { + return this.version +} -/** - * 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 _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) } -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) } -module.exports = isString; +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } -/***/ }), + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} -/***/ 94499: -/***/ ((module) => { +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} -/** Used for built-in method references. */ -var objectProto = Object.prototype; +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} -/** - * 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 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 - * - * 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; - }; +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) } -/** - * 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 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ -function once(func) { - return before(2, func); +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) } -/** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) } -/** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @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 - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.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; +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 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 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.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; +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} - return result === result ? (remainder ? result - remainder : result) : 0; +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.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); +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 } -module.exports = once; +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} -/***/ }), +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b -/***/ 90250: -/***/ (function(module, exports, __nccwpck_require__) { + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b -/* module decorator */ module = __nccwpck_require__.nmd(module); -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { + case '': + case '=': + case '==': + return eq(a, b, loose) - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; + case '!=': + return neq(a, b, loose) - /** Used as the semantic version number. */ - var VERSION = '4.17.21'; + case '>': + return gt(a, b, loose) - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; + case '>=': + return gte(a, b, loose) - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function', - INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + case '<': + return lt(a, b, loose) - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; + case '<=': + return lte(a, b, loose) - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; + default: + throw new TypeError('Invalid operator: ' + op) + } +} - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } - /** 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; + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; + debug('comp', this) +} - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } - /** 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; + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } - /** 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] - ]; + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} - /** `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]'; +Comparator.prototype.toString = function () { + return this.value +} - 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]'; +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) - /** 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; + if (this.semver === ANY) { + return true + } - /** 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); + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; + return cmp(version, this.operator, this.semver, this.options) +} - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } - /** Used to match leading whitespace. */ - var reTrimStart = /^\s+/; + var rangeTmp - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} - /** - * Used to validate the `validate` option in `_.template` variable. - * - * Forbids characters which could potentially change the meaning of the function argument definition: - * - "()," (modification of function parameters) - * - "=" (default value) - * - "[]{}" (destructuring of function parameters) - * - "/" (beginning of a comment) - * - whitespace - */ - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + if (range instanceof Comparator) { + return new Range(range.value, options) + } - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; + if (!(this instanceof Range)) { + return new Range(range, options) + } - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; + this.format() +} - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; +Range.prototype.toString = function () { + return this.range +} - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) - /** 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; + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) - /** 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'; + // normalize spaces + range = range.split(/\s+/).join(' ') - /** 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|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + // At this point, the range is completely trimmed and + // ready to be split into comparators. - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) - /** - * 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'); + return set +} - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } - /** 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'); + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} - /** 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 + ']'); +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} - /** 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 ]/; +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} - /** 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' - ]; +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} - /** 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; +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret - /** 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; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } - /** 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' - }; + debug('tilde return', ret) + return ret + }) +} - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; + debug('caret return', ret) + return ret + }) +} - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); + if (gtlt === '=' && anyX) { + gtlt = '' + } - /** Detect free variable `exports`. */ - var freeExports = true && exports && !exports.nodeType && exports; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 - /** Detect free variable `module`. */ - var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; + debug('xRange return', ret) - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; + return ret + }) +} - if (types) { - return types; - } +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } - /* 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; + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } - /*--------------------------------------------------------------------------*/ + return (from + ' ' + to).trim() +} - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @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); +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false } - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @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; + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true } - return accumulator; } + return false +} - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false } - return array; } - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } } } - return array; + + // Version has a -pre, but it's not one of the ones we like. + return false } - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array 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 arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + return true +} - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false } + return range.test(version) +} - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) } } - return result; + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver } - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver } - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @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; + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] - while (++index < length) { - if (comparator(value, array[index])) { - return true; + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) } - } - return false; + }) } - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); + if (minver && range.test(minver)) { + return minver + } - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null } +} - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) - while (++index < length) { - array[offset + index] = values[index]; + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } - return array; } + return true +} - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version } - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; + if (typeof version !== 'string') { + return null } - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array 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 arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + var match = version.match(re[COERCE]) - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; + if (match == null) { + return null } - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } +/***/ }), - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; +/***/ 82022: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var timespan = __nccwpck_require__(46098); +var PS_SUPPORTED = __nccwpck_require__(59085); +var jws = __nccwpck_require__(4636); +var includes = __nccwpck_require__(17931); +var isBoolean = __nccwpck_require__(16501); +var isInteger = __nccwpck_require__(21441); +var isNumber = __nccwpck_require__(40298); +var isPlainObject = __nccwpck_require__(25723); +var isString = __nccwpck_require__(25180); +var once = __nccwpck_require__(94499); + +var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] +if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} + +var sign_options_schema = { + expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } +}; + +var registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } +}; + +function validate(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); + } + Object.keys(object) + .forEach(function(key) { + var validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); } }); - return result; +} + +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); +} + +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} + +var options_to_payload = { + 'audience': 'aud', + 'issuer': 'iss', + 'subject': 'sub', + 'jwtid': 'jti' +}; + +var options_for_objects = [ + 'expiresIn', + 'notBefore', + 'noTimestamp', + 'audience', + 'issuer', + 'subject', + 'jwtid', +]; + +module.exports = function (payload, secretOrPrivateKey, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else { + options = options || {}; } - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + var isObjectPayload = typeof payload === 'object' && + !Buffer.isBuffer(payload); - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } + var header = Object.assign({ + alg: options.algorithm || 'HS256', + typ: isObjectPayload ? 'JWT' : undefined, + kid: options.keyid + }, options.header); + + function failure(err) { + if (callback) { + return callback(err); } - return -1; + throw err; } - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); + if (!secretOrPrivateKey && options.algorithm !== 'none') { + return failure(new Error('secretOrPrivateKey must have a value')); } - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; + if (typeof payload === 'undefined') { + return failure(new Error('payload is required')); + } else if (isObjectPayload) { + try { + validatePayload(payload); + } + catch (error) { + return failure(error); + } + if (!options.mutatePayload) { + payload = Object.assign({},payload); + } + } else { + var invalid_options = options_for_objects.filter(function (opt) { + return typeof options[opt] !== 'undefined'; + }); - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } + if (invalid_options.length > 0) { + return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); } - return -1; } - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; + if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); } - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; + if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); } - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; + try { + validateOptions(options); } - - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; + catch (error) { + return failure(error); } - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } + var timestamp = payload.iat || Math.floor(Date.now() / 1000); - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } - array.sort(comparer); - while (length--) { - array[length] = array[length].value; + if (typeof options.notBefore !== 'undefined') { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.nbf === 'undefined') { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); } - return array; } - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; + if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.exp === 'undefined') { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); + Object.keys(options_to_payload).forEach(function (key) { + var claim = options_to_payload[key]; + if (typeof options[key] !== 'undefined') { + if (typeof payload[claim] !== 'undefined') { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); } + payload[claim] = options[key]; } - return result; + }); + + var encoding = options.encoding || 'utf8'; + + if (typeof callback === 'function') { + callback = callback && once(callback); + + jws.createSign({ + header: header, + privateKey: secretOrPrivateKey, + payload: payload, + encoding: encoding + }).once('error', callback) + .once('done', function (signature) { + callback(null, signature); + }); + } else { + return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); } +}; - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - while (++index < n) { - result[index] = iteratee(index); - } - return result; +/***/ }), + +/***/ 12327: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var JsonWebTokenError = __nccwpck_require__(405); +var NotBeforeError = __nccwpck_require__(4383); +var TokenExpiredError = __nccwpck_require__(46637); +var decode = __nccwpck_require__(53359); +var timespan = __nccwpck_require__(46098); +var PS_SUPPORTED = __nccwpck_require__(59085); +var jws = __nccwpck_require__(4636); + +var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; +var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +var HS_ALGS = ['HS256', 'HS384', 'HS512']; + +if (PS_SUPPORTED) { + PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); + RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} + +module.exports = function (jwtString, secretOrPublicKey, options, callback) { + if ((typeof options === 'function') && !callback) { + callback = options; + options = {}; } - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); + if (!options) { + options = {}; } - /** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ - function baseTrim(string) { - return string - ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') - : string; - } + //clone this object since we are going to mutate it. + options = Object.assign({}, options); - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); + var done; + + if (callback) { + done = callback; + } else { + done = function(err, data) { + if (err) throw err; + return data; }; } - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); + if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { + return done(new JsonWebTokenError('clockTimestamp must be a number')); } - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); + if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { + return done(new JsonWebTokenError('nonce must be a non-empty string')); } - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; + var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; + if (!jwtString){ + return done(new JsonWebTokenError('jwt must be provided')); } - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @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; + if (typeof jwtString !== 'string') { + return done(new JsonWebTokenError('jwt must be a string')); } - /** - * 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; + var parts = jwtString.split('.'); - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; + if (parts.length !== 3){ + return done(new JsonWebTokenError('jwt malformed')); } - /** - * 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); - - /** - * 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 decodedToken; - /** - * 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]; + try { + decodedToken = decode(jwtString, { complete: true }); + } catch(err) { + return done(err); } - /** - * 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]; + if (!decodedToken) { + return done(new JsonWebTokenError('invalid token')); } - /** - * 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); - } + var header = decodedToken.header; + var getSecret; - /** - * 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); + if(typeof secretOrPublicKey === 'function') { + if(!callback) { + return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); + } + + getSecret = secretOrPublicKey; + } + else { + getSecret = function(header, secretCallback) { + return secretCallback(null, secretOrPublicKey); + }; } - /** - * 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 = []; + return getSecret(header, function(err, secretOrPublicKey) { + if(err) { + return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); + } - while (!(data = iterator.next()).done) { - result.push(data.value); + var hasSignature = parts[2].trim() !== ''; + + if (!hasSignature && secretOrPublicKey){ + return done(new JsonWebTokenError('jwt signature is required')); } - 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); + if (hasSignature && !secretOrPublicKey) { + return done(new JsonWebTokenError('secret or public key must be provided')); + } - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } + if (!hasSignature && !options.algorithms) { + options.algorithms = ['none']; + } - /** - * 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)); - }; - } + if (!options.algorithms) { + options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || + ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : + ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @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; - } + if (!~options.algorithms.indexOf(decodedToken.header.alg)) { + return done(new JsonWebTokenError('invalid algorithm')); } - return result; - } - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); + var valid; - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } + try { + valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); + } catch (e) { + return done(e); + } - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); + if (!valid) { + return done(new JsonWebTokenError('invalid signature')); + } - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } + var payload = decodedToken.payload; - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; + if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { + if (typeof payload.nbf !== 'number') { + return done(new JsonWebTokenError('invalid nbf value')); + } + if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { + return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); + } + } - while (++index < length) { - if (array[index] === value) { - return index; + if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { + if (typeof payload.exp !== 'number') { + return done(new JsonWebTokenError('invalid exp value')); + } + if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); } } - return -1; - } - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; + if (options.audience) { + var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; + var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + + var match = target.some(function (targetAudience) { + return audiences.some(function (audience) { + return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; + }); + }); + + if (!match) { + return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); } } - return index; - } - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } + if (options.issuer) { + var invalid_issuer = + (typeof options.issuer === 'string' && payload.iss !== options.issuer) || + (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } + if (invalid_issuer) { + return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); + } + } - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - function trimmedEndIndex(string) { - var index = string.length; + if (options.subject) { + if (payload.sub !== options.subject) { + return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); + } + } - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index; - } + if (options.jwtid) { + if (payload.jti !== options.jwtid) { + return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); + } + } - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + if (options.nonce) { + if (payload.nonce !== options.nonce) { + return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); + } + } - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; + if (options.maxAge) { + if (typeof payload.iat !== 'number') { + return done(new JsonWebTokenError('iat required when maxAge is specified')); + } + + var maxAgeTimestamp = timespan(options.maxAge, payload.iat); + if (typeof maxAgeTimestamp === 'undefined') { + return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); + } } - return result; - } - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } + if (options.complete === true) { + var signature = decodedToken.signature; + + return done(null, { + header: header, + payload: payload, + signature: signature + }); + } - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } + return done(null, payload); + }); +}; - /*--------------------------------------------------------------------------*/ - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); +/***/ }), - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; +/***/ 96010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +var bufferEqual = __nccwpck_require__(9239); +var Buffer = __nccwpck_require__(21867).Buffer; +var crypto = __nccwpck_require__(76417); +var formatEcdsa = __nccwpck_require__(11728); +var util = __nccwpck_require__(31669); - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } - /** Used to generate unique IDs. */ - var idCounter = 0; + if (typeof key === 'string') { + return; + } - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); + if (typeof key === 'string') { + return; + } - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + if (typeof key === 'object') { + return; + } - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; + throw typeError(MSG_INVALID_SIGNER_KEY); +}; - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; + if (typeof key === 'string') { + return key; + } - /** Used to lookup unminified function names. */ - var realNames = {}; + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } - /*------------------------------------------------------------------------*/ + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 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); - } +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - /** - * 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; - }; - }()); +function toBase64(base64url) { + base64url = base64url.toString(); - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; } + } - /** - * 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; - } + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} - /** - * 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 = { +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} - /*------------------------------------------------------------------------*/ +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} - /** - * 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__ = []; - } +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} - /** - * 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; - } +function createNoneSigner() { + return function sign() { + return ''; + } +} - /** - * 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; - } +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} - /** - * 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__); +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; - outer: - while (length-- && resIndex < takeCount) { - index += dir; - var iterIndex = -1, - value = array[index]; +/***/ }), - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); +/***/ 4636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } +/*global exports*/ +var SignStream = __nccwpck_require__(73334); +var VerifyStream = __nccwpck_require__(5522); - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; - /*------------------------------------------------------------------------*/ +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +/***/ }), - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } +/***/ 61868: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } +/*global module, process*/ +var Buffer = __nccwpck_require__(21867).Buffer; +var Stream = __nccwpck_require__(92413); +var util = __nccwpck_require__(31669); - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } - /*------------------------------------------------------------------------*/ + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } +module.exports = DataStream; - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } +/***/ }), - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +/***/ 73334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return index < 0 ? undefined : data[index][1]; - } +/*global module*/ +var Buffer = __nccwpck_require__(21867).Buffer; +var DataStream = __nccwpck_require__(61868); +var jwa = __nccwpck_require__(96010); +var Stream = __nccwpck_require__(92413); +var toString = __nccwpck_require__(65292); +var util = __nccwpck_require__(31669); - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - /** - * 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); +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; +function SignStream(opts) { + var secret = opts.secret||opts.privateKey||opts.key; + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); - /*------------------------------------------------------------------------*/ +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; - /** - * 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; +SignStream.sign = jwsSign; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +module.exports = SignStream; - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } +/***/ }), - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } +/***/ 65292: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } +/*global module*/ +var Buffer = __nccwpck_require__(64293).Buffer; - /** - * Sets the map `key` to `value`. - * - * @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; +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; - 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; +/***/ }), - /*------------------------------------------------------------------------*/ +/***/ 5522: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; +/*global module*/ +var Buffer = __nccwpck_require__(21867).Buffer; +var DataStream = __nccwpck_require__(61868); +var jwa = __nccwpck_require__(96010); +var Stream = __nccwpck_require__(92413); +var toString = __nccwpck_require__(65292); +var util = __nccwpck_require__(31669); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} - /*------------------------------------------------------------------------*/ +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} - this.size = data.size; - return result; - } +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } + if (!isValidJws(jwsSig)) + return null; - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } + var header = headerFromJWS(jwsSig); - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } + if (!header) + return null; - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); - /*------------------------------------------------------------------------*/ + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret||opts.publicKey||opts.key; + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } +module.exports = VerifyStream; - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } +/***/ }), - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } +/***/ 75978: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } +"use strict"; - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } +const path = __nccwpck_require__(85622); +const fs = __nccwpck_require__(77758); +const stripBom = __nccwpck_require__(89383); +const parseJson = __nccwpck_require__(81680); +const pify = __nccwpck_require__(64810); - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } +const parse = (data, filePath, options = {}) => { + data = stripBom(data); - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } + if (typeof options.beforeParse === 'function') { + data = options.beforeParse(data); + } - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } + return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); +}; - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; +const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } +module.exports = loadJsonFile; +module.exports.default = loadJsonFile; +module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @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. - * - * @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; +/***/ 81680: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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, 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); +"use strict"; - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - } +const errorEx = __nccwpck_require__(23505); +const fallback = __nccwpck_require__(55586); - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); +const JSONError = errorEx('JSONError', { + fileName: errorEx.append('in %s') +}); - 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; - } +module.exports = (input, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } - /** - * 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); - }; - } + try { + try { + return JSON.parse(input, reviver); + } catch (err) { + fallback(input, reviver); - /** - * 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]; + throw err; + } + } catch (err) { + err.message = err.message.replace(/\n/g, ''); - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } + const jsonErr = new JSONError(err); + if (filename) { + jsonErr.fileName = filename; + } - /** - * 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); - } + throw jsonErr; + } +}; - /** - * 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 (++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; - } +/***/ 89383: +/***/ ((module) => { - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @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); +"use strict"; - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @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); +module.exports = x => { + if (typeof x !== 'string') { + throw new TypeError('Expected a string, got ' + typeof x); + } - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @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; - } + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (x.charCodeAt(0) === 0xFEFF) { + return x.slice(1); + } - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @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; + return x; +}; - 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. - * - * @private - * @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; +/***/ 11289: +/***/ ((module) => { - 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; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * 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; - } +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /** - * 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; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - predicate || (predicate = isFlattenable); - result || (result = []); +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - 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; - } +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @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); +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - /** - * 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(); + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} - /** - * 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); +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * 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); - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * 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); - } +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * 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]); - }); - } +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - /** - * 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); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; - var index = 0, - length = path.length; +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } + var length = result.length, + skipIndexes = !!length; - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @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)); + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); } + } + return result; +} - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @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); - } +/** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @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 assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; +} - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @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; - } +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; + } +} - /** - * 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 `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @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 = []; - /** - * 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); + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); } + } + return result; +} - /** - * 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 < nativeMax(start, end); +/** + * 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) { + 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] = array; + return apply(func, this, otherArgs); + }; +} - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @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 = []; +/** + * Copies properties of `source` to `object`. + * + * @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) { + object || (object = {}); - 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, + length = props.length; - var index = -1, - seen = caches[0]; + while (++index < length) { + var key = props[index]; - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; - 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; - } + assignValue(object, key, newValue === undefined ? source[key] : newValue); + } + return object; +} - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @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; - } +/** + * Creates a function like `_.assign`. + * + * @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; - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @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); - } + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; - /** - * The base implementation of `_.isArguments`. - * - * @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; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; } - - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @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; + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } } + return object; + }); +} - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @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; - } +/** + * Checks if `value` is a valid array-like index. + * + * @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); +} - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @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); - } +/** + * Checks if the given arguments are from an iteratee call. + * + * @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 likely a prototype object. + * + * @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; - /** - * 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. - * - * @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); + return value === proto; +} - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @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; +} - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; +/** + * 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 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 + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - 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__'); +/** + * Checks if `value` is likely an `arguments` 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`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; +/** + * Checks if `value` is classified as an `Array` object. + * + * @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 + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - 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); - } +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @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; - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @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`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @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; +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - 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]; +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @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 + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - 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; - } +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @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)); - } +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @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; - } +/** + * 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 mutates `object`. + * + * @static + * @memberOf _ + * @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 customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * 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); +}); - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @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; - } +/** + * 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. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @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, assignInDefaults); + return apply(assignInWith, undefined, args); +}); - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @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)]; - } +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * 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 base implementation of `_.iteratee`. - * - * @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); - } +module.exports = defaults; - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @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. - * - * @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; - } +/***/ 48919: +/***/ ((module) => { - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @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`. - */ - function baseLt(value, other) { - return value < other; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @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); - }; - } +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @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); - }; - } +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @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) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - /** - * 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. - * - * @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 = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - var isCommon = newValue === undefined; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - 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) || 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); - } +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @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 `_.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; - /** - * The base implementation of `_.orderBy` without param guards. - * - * @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) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee) { - if (isArray(iteratee)) { - return function(value) { - return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); - } - } - return iteratee; - }); + 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 { - iteratees = [identity]; + arrayPush(result, value); } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @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]); +} + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @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 ? array.length : 0; + return length ? baseFlatten(array, 1) : []; +} + +/** + * Checks if `value` is likely an `arguments` 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`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @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 + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.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.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.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 `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @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 + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @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); - }); - } +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @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 = {}; +module.exports = flatten; - 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. - * - * @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); - }; - } +/***/ 17931: +/***/ ((module) => { - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @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; +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - 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; +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; - /** - * 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; +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - 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; - } +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** - * 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)); - } +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - /** - * 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); +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * 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); +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - return result; - } +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); - /** - * 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 + ''); - } + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} - /** - * 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 `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); - /** - * 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)); + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } + } + return -1; +} - /** - * 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 && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; - 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; + while (++index < length) { + if (array[index] === value) { + return index; } + } + return -1; +} - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @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. - * - * @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 `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} - /** - * The base implementation of `_.shuffle`. - * - * @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 `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @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; + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} - 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; +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - 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)); + }; +} - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @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; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * 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. - * - * @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; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; - /** - * 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). - * - * @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) { - var low = 0, - high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; - value = iteratee(value); - var valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; + var length = result.length, + skipIndexes = !!length; - 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); + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} - 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 `_.keys` which doesn't treat sparse arrays as dense. + * + * @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 `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @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 = []; +/** + * Checks if `value` is a valid array-like index. + * + * @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); +} - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +/** + * Checks if `value` is likely a prototype object. + * + * @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; - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } + return value === proto; +} - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @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; - } +/** + * 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 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 + * + * _.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; - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @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; - } + 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); +} - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @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; +/** + * Checks if `value` is likely an `arguments` 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`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - 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; +/** + * Checks if `value` is classified as an `Array` object. + * + * @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 + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - 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; - } +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** - * The base implementation of `_.unset`. - * - * @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))]; - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @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`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.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 `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - /** - * The base implementation of `_.update`. - * - * @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); - } +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @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 + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @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; +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @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 + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} - /** - * 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. - * - * @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); - } +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @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 + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @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); +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.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; +} - while (++index < length) { - var array = arrays[index], - othIndex = -1; +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.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; - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } + return result === result ? (remainder ? result - remainder : result) : 0; +} - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @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 = {}; +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.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); +} - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } +/** + * Creates an array of the own enumerable property names of `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 _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object ? baseValues(object, keys(object)) : []; +} - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } +module.exports = includes; - /** - * Casts `value` to a path array if it's not one. - * - * @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. - * - * @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. - * - * @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); - } +/***/ 16501: +/***/ ((module) => { - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @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); - }; +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - /** - * Creates a clone of `buffer`. - * - * @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); +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; - buffer.copy(result); - return result; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * Creates a clone of `arrayBuffer`. - * - * @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; - } +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * Creates a clone of `dataView`. - * - * @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); - } +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); +} - /** - * 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; - } +/** + * 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 _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * 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)) : {}; - } +module.exports = isBoolean; - /** - * 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); +/***/ 21441: +/***/ ((module) => { - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > 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; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * 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. - * - * @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; +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - 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; - } +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - /** - * 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; +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - 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; - } +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @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; +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - 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; - } +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - /** - * Copies the values of `source` to `array`. - * - * @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; +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * Copies properties of `source` to `object`. - * - * @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 = {}); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - var index = -1, - length = props.length; +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @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`. + * @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); +} - while (++index < length) { - var key = props[index]; +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @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 + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - /** - * Copies own symbols of `source` to `object`. - * - * @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); - } +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.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 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.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; - /** - * Copies own and inherited symbols of `source` to `object`. - * - * @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); - } + return result === result ? (remainder ? result - remainder : result) : 0; +} - /** - * Creates a function like `_.groupBy`. - * - * @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() : {}; +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.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); +} - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } +module.exports = isInteger; - /** - * Creates a function like `_.assign`. - * - * @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; - }); - } +/***/ 40298: +/***/ ((module) => { - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @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); +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @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; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @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); +/** + * 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 _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } +/** + * 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 _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); +} - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); +module.exports = isNumber; - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); +/***/ }), - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); +/***/ 25723: +/***/ ((module) => { - return chr[methodName]() + trailing; - }; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; - } +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @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); +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } +/** + * 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)); + }; +} - /** - * Creates a function that wraps `func` to enable currying. - * - * @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); +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - 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; - } +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); - /** - * Creates a `_.find` or `_.findLast` function. - * - * @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; - }; - } +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * 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; +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); - 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]; +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * 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 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || + objectToString.call(value) != objectTag || isHostObject(value)) { + 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); +} - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; +module.exports = isPlainObject; - 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; - }; - }); - } +/***/ 25180: +/***/ ((module) => { - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @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); +/** + * lodash 4.0.1 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; +/** `Object#toString` result references. */ +var stringTag = '[object String]'; - 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; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - 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; - } +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * Creates a function like `_.invertBy`. - * - * @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), {}); - }; - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type Function + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** - * Creates a function that performs a mathematical operation on two values. - * - * @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; - }; - } +/** + * 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 _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * Creates a function like `_.over`. - * - * @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); - }); - }); - }); - } +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @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); +module.exports = isString; - 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. - * - * @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; +/***/ 94499: +/***/ ((module) => { - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); - } - return wrapper; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @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); - }; - } +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; - /** - * Creates a function that performs a relational operation on two values. - * - * @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); - }; - } +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - /** - * Creates a function that wraps `func` to continue currying. - * - * @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; +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - 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 - ]; +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - /** - * Creates a function like `_.round`. - * - * @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 && nativeIsFinite(number)) { - // 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)); +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; - } +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - /** - * Creates a set object of `values`. - * - * @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); - }; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @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)); - }; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * 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 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 + * + * 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 either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @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; +/** + * 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 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +function once(func) { + return before(2, func); +} - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); +/** + * 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 Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - 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); +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @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 + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - 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); - } +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.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; +} - /** - * 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`. - * - * @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; - } +/** + * 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 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.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; - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. - * - * @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; - } + return result === result ? (remainder ? result - remainder : result) : 0; +} - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @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; - } +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.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); +} - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @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; +module.exports = once; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - 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]; +/***/ 90250: +/***/ (function(module, exports, __nccwpck_require__) { - 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; - } +/* module decorator */ module = __nccwpck_require__.nmd(module); +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @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; + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; + /** Used as the semantic version number. */ + var VERSION = '4.17.21'; - 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); + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; - case errorTag: - return object.name == other.name && object.message == other.message; + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function', + INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; - 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 + ''); + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; - case mapTag: - var convert = mapToArray; + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; - 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; + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; - // 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; + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } + /** 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; - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @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; + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; - 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; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; - 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; + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - // 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; - } + /** 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; - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @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 + ''); - } + /** 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] + ]; - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @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); - } + /** `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]'; - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @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); - } + 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]'; - /** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; + /** 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; - /** - * Gets the name of `func`. - * - * @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; + /** 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); - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; - /** - * Gets the argument placeholder value for `func`. - * - * @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; - } + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - /** - * 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. - * - * @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; - } + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); - /** - * Gets the data for `map`. - * - * @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; - } + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; - /** - * Gets the property names, values, and compare flags of `object`. - * - * @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; + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; - while (length--) { - var key = result[length], - value = object[key]; + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - /** - * Gets the native function at `key` of `object`. - * - * @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; - } + /** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */ + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @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]; + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @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); - }); - }; + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @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; - }; + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; - // 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) : ''; + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; - 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; - }; - } + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @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; + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - while (++index < length) { - var data = transforms[index], - size = data.size; + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; - 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 }; - } + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - /** - * Extracts wrapper details from the `source` body comment. - * - * @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) : []; - } + /** 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; - /** - * Checks if `path` exists on `object`. - * - * @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); + /** 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'; - var index = -1, - length = path.length, - result = false; + /** 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|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - 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)); - } + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); + /** + * 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'); - // 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; - } + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - /** - * Initializes an object clone. - * - * @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)) - : {}; - } + /** 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'); - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); + /** 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 + ']'); - case boolTag: - case dateTag: - return new Ctor(+object); + /** 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 ]/; - case dataViewTag: - return cloneDataView(object, isDeep); + /** 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' + ]; - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; - case mapTag: - return new Ctor; + /** 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; - case numberTag: - case stringTag: - return new Ctor(object); + /** 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; - case regexpTag: - return cloneRegExp(object); + /** 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' + }; - case setTag: - return new Ctor; + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; - case symbolTag: - return cloneSymbol(object); - } - } + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. - * - * @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'); - } + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @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]); - } + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; - /** - * Checks if `value` is a valid array-like index. - * - * @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) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - /** - * Checks if the given arguments are from an iteratee call. - * - * @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; - } + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); - /** - * Checks if `value` is a property name and not a property path. - * - * @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)); - } + /** Detect free variable `exports`. */ + var freeExports = true && exports && !exports.nodeType && exports; - /** - * Checks if `value` is suitable for use as unique object key. - * - * @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); - } + /** Detect free variable `module`. */ + var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; - /** - * Checks if `func` has a lazy counterpart. - * - * @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]; + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; - /** - * Checks if `func` has its source masked. - * - * @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); - } + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; - /** - * Checks if `func` is capable of being masked. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ - var isMaskable = coreJsData ? isFunction : stubFalse; + if (types) { + return types; + } - /** - * Checks if `value` is likely a prototype object. - * - * @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; + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); - return value === proto; - } + /* 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; - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @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. `===`. - * - * @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 faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @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); + } - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @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; - }); + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @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; - var cache = result.cache; - return result; + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); } + return accumulator; + } - /** - * Merges the function metadata of `source` into `data`. - * - * 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. - * - * @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)); + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; - // 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]; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; } + return array; + } - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @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); - } + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; } - return result; } + return array; + } - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array 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 arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } } + return true; + } - /** - * A specialized version of `baseRest` which transforms the rest 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. - * @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); + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; - 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); - }; + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } } + return result; + } - /** - * Gets the parent value at `path` of `object`. - * - * @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)); - } + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 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. - * - * @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); + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @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 (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + while (++index < length) { + if (comparator(value, array[index])) { + return true; } - return array; } + return false; + } - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); - return object[key]; + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; + } - /** - * Sets metadata for `func`. - * - * **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. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var setData = shortOut(baseSetData); + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). - * - * @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); - }; + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; - /** - * 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. - * - * @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))); + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); } + return accumulator; + } - /** - * 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. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array 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 arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } } + return false; + } - /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. - * - * @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; + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } - array[rand] = array[index]; - array[index] = value; - } - array.length = size; - return array; - } + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; }); + return result; + } - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @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; - } + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); - /** - * Converts `func` to its source code. - * - * @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) {} + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } - return ''; } + return -1; + } - /** - * Updates wrapper `details` based on `bitmask` flags. - * - * @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(); - } + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } - /** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; } + return -1; + } - /*------------------------------------------------------------------------*/ + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } - /** - * 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. - * - * @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. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['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)); + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; } + return array; + } - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @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 = []; + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); } - return result; } + return result; + } - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @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. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [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; + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + while (++index < n) { + result[index] = iteratee(index); } + return result; + } - /** - * 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. - * @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)) - : []; + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; }); + } - /** - * 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)) - : []; + /** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ + function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') + : string; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -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. + * + * @private + * @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; + } - /** - * 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. - * @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) - : []; - }); + /** + * 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; - /** - * 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 []; + while (length--) { + if (array[length] === placeholder) { + ++result; } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); } + return result; + } - /** - * 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); - } + /** + * 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); - /** - * 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) - : []; - } + /** + * 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); - /** - * 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). - * - * @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': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // 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) - : []; - } + /** + * 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]; + } - /** - * 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); - } + /** + * 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]; + } - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @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 - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // 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); - } + /** + * 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); + } - /** - * This method is like `_.findIndex` 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 - * - * // 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); - } + /** + * 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); + } - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @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) : []; - } + /** + * 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 = []; - /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @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) : []; + while (!(data = iterator.next()).done) { + result.push(data.value); } + return result; + } - /** - * Recursively flatten `array` up to `depth` times. - * - * @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 - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] - * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + /** + * 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; + } + + /** + * 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)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @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; } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); } + return result; + } - /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example - * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; - } - return result; - } + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); - /** - * 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`. - * - * @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 - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // 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); + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; } - return baseIndexOf(array, value, index); } + return -1; + } - /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } } + return index; + } - /** - * 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. - * - * @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 - * - * _.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) - : []; - }); + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } - /** - * 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). - * - * @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 - * - * _.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); + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedEndIndex(string) { + var index = string.length; - /** - * 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 the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; + } - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @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 - * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; } + return result; + } - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @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 - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 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); - } + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @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 - * - * 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. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @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 - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @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 - * - * 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; - } + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); /** - * 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`. - * - * @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 - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; - } + var nativeObjectToString = objectProto.toString; - /** - * 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). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @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 - * - * 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; - } + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); - /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @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 - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] - * - * console.log(pulled); - * // => ['b', 'd'] - */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); - return result; - }); + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; - /** - * 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). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @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 - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] - * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); - 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; - } + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `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); - } + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. - * - * @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); - } + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. * - * @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 + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. * - * _.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). + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. * - * @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 + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 + * In addition to lodash methods, wrappers have `Array` and `String` methods. * - * // 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`. + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * - * @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 + * The wrapper `String` methods are: + * `replace` and `split` * - * _.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. + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * - * @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`. - * @example + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` * - * _.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). + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` * - * @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`. + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * function square(n) { + * return n * n; + * } * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 + * var wrapped = _([1, 2, 3]); * - * // 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`. + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 * - * @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 + * // Returns a wrapped value. + * var squares = wrapped.map(square); * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true */ - 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; + 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 -1; + return new LodashWrapper(value); } /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example + * The base implementation of `_.create` without support for assigning + * properties to the created object. * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } + 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; + }; + }()); /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @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 + * The function whose prototype chain sequence wrappers inherit from. * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] + * @private */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; + function baseLodash() { + // No operation performed. } /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * The base constructor for creating `lodash` wrapper objects. * - * _.tail([1, 2, 3]); - * // => [2, 3] + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; } /** - * Creates a slice of `array` with `n` elements taken from the beginning. + * 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 _ - * @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 - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.take([1, 2, 3], 0); - * // => [] + * @type {Object} */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; + 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 } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); - } + }; + + // 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 slice of `array` with `n` elements taken 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 take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * - * _.takeRight([1, 2, 3], 0); - * // => [] + * @private + * @constructor + * @param {*} value The value to wrap. */ - 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); + 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 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 - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] + * Creates a clone of the lazy wrapper object. * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; + 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; } /** - * 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). - * - * @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': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] + * Reverses the direction of lazy iteration. * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; + 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; } /** - * 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. - * - * @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 + * Extracts the unwrapped value from its lazy wrapper. * - * _.union([2], [1, 2]); - * // => [2, 1] + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); + 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__); - /** - * 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). - * - * @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 - * - * _.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; + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); + var result = []; - /** - * 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). - * - * @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 - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.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); - }); + outer: + while (length-- && resIndex < takeCount) { + index += dir; - /** - * 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. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; } + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + /** - * 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). - * - * @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] + * Creates a hash object. * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } /** - * 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). - * - * @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 - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * Removes all key-value entries from the hash. * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + * @private + * @name clear + * @memberOf Hash */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; } /** - * 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. - * - * @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 - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * Removes `key` and its value from the hash. * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `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)); - }); + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; } /** - * 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). - * - * @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 - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] + * Gets the hash value for `key`. * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); + return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @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 + * Checks if a hash value for `key` exists. * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } /** - * 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. - * - * @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 + * Sets the hash `key` to `value`. * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ /** - * 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). - * - * @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 - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] + * Creates an list cache object. * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - 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). - * - * @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 - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * Removes all key-value entries from the list cache. * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + * @private + * @name clear + * @memberOf ListCache */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } /** - * 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. - * - * @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 + * Removes `key` and its value from the list cache. * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - var zip = baseRest(unzip); + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @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 + * Gets the list cache value for `key`. * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; } /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @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 + * Checks if a list cache value for `key` exists. * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } /** - * 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). - * - * @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 + * Sets the list cache `key` to `value`. * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] + * @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. */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); + 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 `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. + * Creates a map cache object to store key-value pairs. * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example + * @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 < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; 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. + * Gets the map value for `key`. * - * @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 + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function tap(value, interceptor) { - interceptor(value); - return value; + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @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; + + /*------------------------------------------------------------------------*/ + /** - * 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 Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example + * Creates an array cache object to store unique values. * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] + * @private + * @constructor + * @param {Array} [values] The values to cache. */ - function thru(value, interceptor) { - return interceptor(value); + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } } /** - * This method is the wrapper version of `_.at`. - * - * @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 + * Adds `value` to the array cache. * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; + function setCacheHas(value) { + return this.__data__.has(value); + } - 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; - }); - }); + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } + * Creates a stack cache object to store key-value pairs. * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function wrapperChain() { - return chain(this); + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; } /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 + * Removes all key-value entries from the stack. * - * console.log(array); - * // => [1, 2, 3] + * @private + * @name clear + * @memberOf Stack */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; } /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } + * Removes `key` and its value from the stack. * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - 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__++]; + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); - return { 'done': done, 'value': value }; + this.size = data.size; + return result; } /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example + * Gets the stack value for `key`. * - * var wrapped = _([1, 2]); + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. * - * wrapped[Symbol.iterator]() === wrapped; - * // => true + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. * - * Array.from(wrapped); - * // => [1, 2] + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. */ - function wrapperToIterator() { + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; return this; } + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] + * Creates an array of the enumerable property names of the array-like `value`. * - * wrapped.value(); - * // => [1, 4] + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. */ - function wrapperPlant(value) { - var result, - parent = this; + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); } - 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.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] + * A specialized version of `_.sample` for arrays. * - * console.log(array); - * // => [3, 2, 1] + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. */ - 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); + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; } /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example + * A specialized version of `_.sampleSize` for arrays. * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } - /*------------------------------------------------------------------------*/ - /** - * 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 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 + * A specialized version of `_.shuffle` for arrays. * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - }); + } /** - * 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). - * - * **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 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`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } } - return func(collection, getIteratee(predicate, 3)); + return -1; } /** - * 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. + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection + * @private * @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 - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; } /** - * 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 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`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - var find = createFind(findIndex); + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @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`. - * @example + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - var findLast = createFind(findLastIndex); + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } /** - * 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 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 - * - * function duplicate(n) { - * return [n, n]; - * } + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } } /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @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. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * The base implementation of `_.at` without support for individual paths. * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; } /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @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. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * The base implementation of `_.clamp` which doesn't coerce arguments. * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] + * @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 flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); + 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; } /** - * 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`. - * - * **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 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 - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * @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 forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); + 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, 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); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + 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; } /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @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 - * @example + * The base implementation of `_.conforms` which doesn't clone `source`. * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; } /** - * 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 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 - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } + * The base implementation of `_.conformsTo` which accepts `props` to check. * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } + * @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`. */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); + 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; + } /** - * 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 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 - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true + * @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. * - * _.includes('abcd', 'bc'); - * // => true + * @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 includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); + 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 isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + return result; } /** - * 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`. + * The base implementation of `_.forEach` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection + * @private * @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 - * - * _.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']] + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - 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; - }); + var baseEach = createBaseEach(baseForOwn); /** - * 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). + * The base implementation of `_.forEachRight` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection + * @private * @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 - * - * 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 } } - * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); + var baseEachRight = createBaseEach(baseForOwnRight, true); /** - * 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` + * The base implementation of `_.every` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection + * @private * @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 - * - * 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) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; } /** - * 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 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 - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. * - * // 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]] + * @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 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]; + 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 baseOrderBy(collection, iteratees, orders); + return result; } /** - * 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 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 - * - * 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 base implementation of `_.fill` without an iteratee call guard. * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] + * @private + * @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`. */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); + 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; + } /** - * 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` + * The base implementation of `_.filter` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection + * @private * @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 - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.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) + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; } /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @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 - * @example - * - * var array = [[0, 1], [2, 3], [4, 5]]; + * The base implementation of `_.flatten` with support for restricting flattening. * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] + * @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 reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + 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 opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @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 - * @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'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] + * 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`. * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] + * @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`. */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } + var baseFor = createBaseFor(); /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. * - * _.sample([1, 2, 3, 4]); - * // => 2 + * @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`. */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } + var baseForRight = createBaseFor(true); /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @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. - * @example - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] + * The base implementation of `_.forOwn` without support for iteratee shorthands. * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - 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); + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); } /** - * 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 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); } /** - * 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 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. * - * _.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; + * @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]); + }); } /** - * 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 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, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true + * The base implementation of `_.get` without support for default values. * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true + * @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 some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + 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 func(collection, getIteratee(predicate, 3)); + return (index && index == length) ? object : undefined; } /** - * 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 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 users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 }, - * { 'user': 'barney', 'age': 34 } - * ]; + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * @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. * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - 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]]; + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - - /*------------------------------------------------------------------------*/ + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } /** - * 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 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example + * The base implementation of `_.gt` which doesn't coerce arguments. * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. + * @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`. */ - var now = ctxNow || function() { - return root.Date.now(); - }; - - /*------------------------------------------------------------------------*/ + function baseGt(value, other) { + return value > other; + } /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @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. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); + * The base implementation of `_.has` without support for deep paths. * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. + * @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 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); - } - }; + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); } /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @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. - * @example + * The base implementation of `_.hasIn` without support for deep paths. * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] + * @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 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); + function baseHasIn(object, key) { + return object != null && key in Object(object); } /** - * 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. + * The base implementation of `_.inRange` which doesn't coerce arguments. * - * @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 + * @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. * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. + * @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 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); + 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)); } - if (n <= 1) { - func = undefined; + 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; - }; + } + 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 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 - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' + * @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`. */ - 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); - }); + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * 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 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 - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' + * The base implementation of `_.invoke` without support for individual + * method arguments. * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' + * @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. */ - 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); - }); + 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); + } /** - * 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 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. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] + * The base implementation of `_.isArguments`. * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ - 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; + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; } /** - * 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 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. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * - * curried(1, 2, 3); - * // => [1, 2, 3] + * @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. * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ - 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; + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; } /** - * 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. - * - * **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. - * - * 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 `_.debounce` and `_.throttle`. - * - * @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. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // 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 base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); + * @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 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 baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; } - - 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; + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; - - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } + /** + * 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. + * + * @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); - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; - // 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)); - } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); + 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__'); - function trailingEdge(time) { - timerId = undefined; + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } - lastArgs = lastThis = undefined; - return result; } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; + if (!isSameTag) { + return false; } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @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; + } - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @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; - lastArgs = arguments; - lastThis = this; - lastCallTime = time; + 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 (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; } - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); + } 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; } } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - return result; } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; + return true; } /** - * 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 Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example + * The base implementation of `_.isNative` without bad shim checks. * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @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. - * @example + * The base implementation of `_.isRegExp` without Node.js optimizations. * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } /** - * Creates a function that invokes `func` with arguments reversed. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example - * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); + * The base implementation of `_.isSet` without Node.js optimizations. * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; } /** - * 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 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 - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] + * The base implementation of `_.isTypedArray` without Node.js optimizations. * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] + * @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`. * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); + 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; } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } - if (cache.has(key)) { - return cache.get(key); + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @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); } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; + } + return result; } - // 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 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); } - 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]); + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); } - return !predicate.apply(this, args); - }; + } + return result; } /** - * 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 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example + * The base implementation of `_.lt` which doesn't coerce arguments. * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once + * @private + * @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`. */ - function once(func) { - return before(2, func); + function baseLt(value, other) { + return value < other; } /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] + * The base implementation of `_.map` without support for iteratee shorthands. * - * func(10, 5); - * // => [100, 10] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. */ - 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); + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); }); - }); + return result; + } /** - * 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. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @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. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' + * The base implementation of `_.matches` which doesn't clone `source`. * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); + 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); + }; + } /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @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. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); + 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); + }; + } /** - * 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 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 - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); + * The base implementation of `_.merge` without support for multiple sources. * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] + * @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. */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } /** - * 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 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 - * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); + * 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. * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' + * @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 rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); + 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) || 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); } /** - * 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 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 say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' + * The base implementation of `_.nth` which doesn't coerce arguments. * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); + * @private + * @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. * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 + * @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 spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity]; } - 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); + var index = -1; + iteratees = arrayMap(iteratees, 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); }); } /** - * 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 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); + * The base implementation of `_.pick` without support for individual + * property identifiers. * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. */ - 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 + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); }); } /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example + * The base implementation of `_.pickBy` without support for iteratee shorthands. * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] + * @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 unary(func) { - return ary(func, 1); + 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; } /** - * 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. - * - * @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. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); + * A specialized version of `baseProperty` which supports deep paths. * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; } - /*------------------------------------------------------------------------*/ - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. */ - function castArray() { - if (!arguments.length) { - return []; + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); } - var value = arguments[0]; - return isArray(value) ? value : [value]; + 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; } /** - * Creates a shallow clone of `value`. - * - * **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. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); + 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; } /** - * 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]). - * - * @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 - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); + * The base implementation of `_.random` without support for returning + * floating-point numbers. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false + * @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 cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + 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; } /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @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 - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); + * The base implementation of `_.repeat` which doesn't coerce arguments. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 + * @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 cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + 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; } /** - * 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 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 - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true + * The base implementation of `_.rest` which doesn't validate or coerce arguments. * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false + * @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 conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); } /** - * 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 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 - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false + * The base implementation of `_.sample`. * - * _.eq(NaN, NaN); - * // => true + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. */ - function eq(value, other) { - return value === other || (value !== value && other !== other); + function baseSample(collection) { + return arraySample(values(collection)); } /** - * Checks if `value` is greater than `other`. - * - * @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 - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false + * The base implementation of `_.sampleSize` without param guards. * - * _.gt(1, 3); - * // => false + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - var gt = createRelationalOperation(baseGt); + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } /** - * Checks if `value` is greater than or equal to `other`. - * - * @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 - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true + * The base implementation of `_.set`. * - * _.gte(1, 3); - * // => false + * @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`. */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); + 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 (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + 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; + } /** - * Checks if `value` is likely an `arguments` 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`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true + * The base implementation of `setData` without support for hot loop shorting. * - * _.isArguments([1, 2, 3]); - * // => false + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; }; /** - * Checks if `value` is classified as an `Array` object. - * - * @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 - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false + * The base implementation of `setToString` without support for hot loop shorting. * - * _.isArray(_.noop); - * // => false + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. */ - var isArray = Array.isArray; + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @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`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true + * The base implementation of `_.shuffle`. * - * _.isArrayBuffer(new Array(2)); - * // => false + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } /** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true + * The base implementation of `_.slice` without an iteratee call guard. * - * _.isArrayLike(_.noop); - * // => false + * @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 isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + 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; } /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. + * The base implementation of `_.some` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, + * @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`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; } /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @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`. - * @example - * - * _.isBoolean(false); - * // => true + * 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. * - * _.isBoolean(null); - * // => false + * @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 isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); + 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); } /** - * Checks if `value` is a buffer. - * - * @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`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true + * 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). * - * _.isBuffer(new Uint8Array(2)); - * // => false + * @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`. */ - var isBuffer = nativeIsBuffer || stubFalse; + function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var 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); + } /** - * Checks if `value` is classified as a `Date` 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`. - * @example - * - * _.isDate(new Date); - * // => true + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. * - * _.isDate('Mon April 23 2012'); - * // => false + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + 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; + } /** - * Checks if `value` is likely a DOM element. - * - * @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`. - * @example - * - * _.isElement(document.body); - * // => true + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. * - * _.isElement(''); - * // => false + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. * - * _.isEmpty({ 'a': 1 }); - * // => false + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. */ - 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; + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; } - if (isPrototype(value)) { - return !baseKeys(value).length; + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; } - return true; + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * 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 + * The base implementation of `_.uniqBy` without support for iteratee shorthands. * - * object === other; - * // => false + * @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 isEqual(value, other) { - return baseIsEqual(value, other); + 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; } /** - * 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 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']; + * The base implementation of `_.unset`. * - * _.isEqualWith(array, other, customizer); - * // => true + * @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 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; + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; } /** - * 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 - * - * _.isError(new Error); - * // => true + * The base implementation of `_.update`. * - * _.isError(Error); - * // => false + * @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 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)); + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @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`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. * - * _.isFinite('3'); - * // => false + * @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 isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); + 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)); } /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true + * 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. * - * _.isFunction(/abc/); - * // => false + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. */ - function isFunction(value) { - if (!isObject(value)) { - return false; + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); } - // 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; + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); } /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @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`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. * - * _.isInteger('3'); - * // => false + * @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 isInteger(value) { - return typeof value == 'number' && value == toInteger(value); + 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); } /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @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 - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * - * _.isLength('3'); - * // => false + * @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 isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + 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; } /** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true + * Casts `value` to an empty array if it's not an array like object. * - * _.isObject(null); - * // => false + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; } /** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false + * Casts `value` to `identity` if it's not a function. * - * _.isObjectLike(null); - * // => false + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; + function castFunction(value) { + return typeof value == 'function' ? value : identity; } /** - * Checks if `value` is classified as a `Map` 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`. - * @example - * - * _.isMap(new Map); - * // => true + * Casts `value` to a path array if it's not one. * - * _.isMap(new WeakMap); - * // => false + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * 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 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 - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. * - * _.isMatch(object, { 'b': 1 }); - * // => false + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } + var castRest = baseRest; /** - * 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 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 - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } - * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; + * Casts `array` to a slice if it's needed. * - * _.isMatchWith(object, source, customizer); - * // => true + * @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 isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); } /** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * - * _.isNaN(undefined); - * // => false + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. */ - 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; - } + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; /** - * 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 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true + * Creates a clone of `buffer`. * - * _.isNative(_); - * // => false + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); } - return baseIsNative(value); + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; } /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true + * Creates a clone of `arrayBuffer`. * - * _.isNull(void 0); - * // => false + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. */ - function isNull(value) { - return value === null; + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; } /** - * Checks if `value` is `null` or `undefined`. - * - * @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 - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true + * Creates a clone of `dataView`. * - * _.isNil(NaN); - * // => false + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. */ - function isNil(value) { - return value == null; + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** - * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true + * Creates a clone of `regexp`. * - * _.isNumber('3'); - * // => false + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; } /** - * 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 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true + * Creates a clone of the `symbol` object. * - * _.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; + * @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)) : {}; } /** - * Checks if `value` is classified as a `RegExp` object. - * - * @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`. - * @example - * - * _.isRegExp(/abc/); - * // => true + * Creates a clone of `typedArray`. * - * _.isRegExp('/abc/'); - * // => false + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } /** - * 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). - * - * @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 - * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false - * - * _.isSafeInteger(Infinity); - * // => false + * Compares values to sort them in ascending order. * - * _.isSafeInteger('3'); - * // => false + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + 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 < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; } /** - * Checks if `value` is classified as a `Set` object. - * - * @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`. - * @example + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. * - * _.isSet(new Set); - * // => true + * 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. * - * _.isSet(new WeakSet); - * // => false + * @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`. */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + 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; + } /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @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 - * - * _.isString('abc'); - * // => true + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. * - * _.isString(1); - * // => false + * @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 isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + 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; } /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @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 - * - * _.isSymbol(Symbol.iterator); - * // => true + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. * - * _.isSymbol('abc'); - * // => false + * @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 isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); + 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; } /** - * Checks if `value` is classified as a typed array. - * - * @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`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true + * Copies the values of `source` to `array`. * - * _.isTypedArray([]); - * // => false + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } /** - * Checks if `value` is `undefined`. - * - * @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 - * - * _.isUndefined(void 0); - * // => true + * Copies properties of `source` to `object`. * - * _.isUndefined(null); - * // => false + * @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 isUndefined(value) { - return value === undefined; + 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; } /** - * Checks if `value` is classified as a `WeakMap` object. - * - * @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 - * - * _.isWeakMap(new WeakMap); - * // => true + * Copies own symbols of `source` to `object`. * - * _.isWeakMap(new Map); - * // => false + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); } /** - * Checks if `value` is classified as a `WeakSet` object. - * - * @static - * @memberOf _ - * @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 - * - * _.isWeakSet(new WeakSet); - * // => true + * Copies own and inherited symbols of `source` to `object`. * - * _.isWeakSet(new Set); - * // => false + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); } /** - * Checks if `value` is less than `other`. - * - * @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 - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false + * Creates a function like `_.groupBy`. * - * _.lt(3, 1); - * // => false + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. */ - var lt = createRelationalOperation(baseLt); + 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); + }; + } /** - * Checks if `value` is less than or equal to `other`. - * - * @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 - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true + * Creates a function like `_.assign`. * - * _.lte(3, 1); - * // => false + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); + 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; + }); + } /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] + * Creates a `baseEach` or `baseEachRight` function. * - * _.toArray(1); - * // => [] + * @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`. * - * _.toArray(null); - * // => [] + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. */ - 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); + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; - return func(value); + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; } /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. * - * _.toFinite('3.2'); - * // => 3.2 + * @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 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; + 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 value === value ? value : 0; + return wrapper; } /** - * 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 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 + * Creates a function like `_.lowerFirst`. * - * _.toInteger('3.2'); - * // => 3 + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); - return result === result ? (remainder ? result - remainder : result) : 0; + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; } /** - * 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 Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 - * - * _.toLength(Infinity); - * // => 4294967295 + * Creates a function like `_.camelCase`. * - * _.toLength('3.2'); - * // => 3 + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; } /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. * - * _.toNumber(Infinity); - * // => Infinity + * @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. * - * _.toNumber('3.2'); - * // => 3.2 + * @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 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; + 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); } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); + return wrapper; } /** - * 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 Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } + * Creates a `_.find` or `_.findLast` function. * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); + 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; + }; } /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 + * Creates a `_.flow` or `_.flowRight` function. * - * _.toSafeInteger('3.2'); - * // => 3 + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); + 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; + }; + }); } /** - * 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' + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. * - * _.toString([1, 2, 3]); - * // => '1,2,3' + * @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 toString(value) { - return value == null ? '' : baseToString(value); - } + 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; + } /** - * 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 _ - * @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 Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } + * Creates a function like `_.invertBy`. * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * @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. * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } + * @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. */ - 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]); + 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; + }; + } /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @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 Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * Creates a function like `_.over`. * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); + 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); + }); + }); + }); + } /** - * 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 mutates `object`. - * - * @static - * @memberOf _ - * @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 customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); + 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); + } /** - * 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 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 - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * @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. */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); + 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 an array of values corresponding to `paths` of `object`. - * - * @static - * @memberOf _ - * @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 object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * Creates a `_.range` or `_.rangeRight` function. * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. */ - var at = flatRest(baseAt); + 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 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 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 - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true + * Creates a function that performs a relational operation on two values. * - * circle instanceof Shape; - * // => true + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; } /** - * 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. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example + * Creates a function that wraps `func` to continue currying. * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * @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. */ - var defaults = baseRest(function(object, sources) { - object = Object(object); + 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; - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; + 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 + ]; - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; + /** + * Creates a function like `_.round`. + * + * @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 && nativeIsFinite(number)) { + // 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)); - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); } - } - - return object; - }); + return func(number); + }; + } /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @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 + * Creates a set object of `values`. * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; /** - * 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 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 users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' + * Creates a `_.toPairs` or `_.toPairsIn` function. * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + 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)); + }; } /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * @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 - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' + * @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 findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } + 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); - /** - * 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.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 - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * 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); + 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); } /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @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 Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * 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`. * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + * @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 forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; } /** - * 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 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 - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * @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 forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); + 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; } /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @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 Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + * @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 forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; } /** - * Creates an array of function property names from own enumerable properties - * of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. * - * _.functions(new Foo); - * // => ['a', 'b'] + * @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 functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); + 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; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + 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; } /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. * - * Foo.prototype.c = _.constant('c'); + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] + * @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 functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); + 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; } /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @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 - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' + * @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 get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; + 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; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + 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; } /** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @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 - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true + * A specialized version of `baseRest` which flattens the rest array. * - * _.has(other, 'a'); - * // => false + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); } /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @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 - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true + * Creates an array of own enumerable property names and symbols of `object`. * - * _.hasIn(object, 'b'); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); } /** - * 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.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - result[value] = key; - }, constant(identity)); + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } /** - * 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.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 - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * Gets metadata for `func`. * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } + * @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`. * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } } - }, getIteratee); + return result; + } /** - * Invokes the method at `path` of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @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 + * Gets the argument placeholder value for `func`. * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * @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. * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] + * @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. */ - var invoke = baseRest(baseInvoke); + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } /** - * Creates an array of the own enumerable property names of `object`. + * Gets the data for `map`. * - * **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. + * @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`. * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object + * @private * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] + * @returns {Array} Returns the match data of `object`. */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(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; } /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. + * Gets the native function at `key` of `object`. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object + * @private * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } /** - * 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 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 + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); + 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 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 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 + * Creates an array of the own enumerable symbols of `object`. * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; + * @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`. * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * @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`. * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); + var getTag = baseGetTag; - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; + // 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; + }; } /** - * 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.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; + * Gets the view, applying any `transforms` to the `start` and `end` positions. * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + * @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. */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); + 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 }; + } /** - * 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). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @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 - * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; + * Extracts wrapper details from the `source` body comment. * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } /** - * 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 is considerably slower than `_.pick`. - * - * @static - * @since 0.1.0 - * @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, 'b': '2', 'c': 3 }; + * Checks if `path` exists on `object`. * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } + * @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`. */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; + 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]; } - 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); + if (result || ++index != length) { + return result; } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new 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; - }); + } /** - * 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 Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * Initializes an object clone. * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; } /** - * Creates an object composed of the picked `object` properties. - * - * @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 + * Initializes an object clone based on its `toStringTag`. * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); + function initCloneByTag(object, tag, 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 new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @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 - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * Inserts wrapper `details` in a comment at the top of the `source` body. * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. */ - function pickBy(object, predicate) { - if (object == null) { - return {}; + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** - * 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 - * @since 0.1.0 - * @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 - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 + * Checks if `value` is a flattenable `arguments` object or array. * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' + * @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. * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' + * @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 result(object, path, defaultValue) { - path = castPath(path, object); + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; - var index = -1, - length = path.length; + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; + /** + * Checks if the given arguments are from an iteratee call. + * + * @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; } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); } - return object; + return false; } /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @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. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 + * Checks if `value` is a property name and not a property path. * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 + * @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 set(object, path, value) { - return object == null ? object : baseSet(object, path, value); + 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)); } /** - * 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 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 - * - * var object = {}; + * Checks if `value` is suitable for use as unique object key. * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); } /** - * 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 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * Checks if `func` has a lazy counterpart. * - * Foo.prototype.c = 3; + * @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. * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ - var toPairs = createToPairs(keys); + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } /** - * 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. + * Checks if `func` is capable of being masked. * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example + * @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. * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * @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. `===`. * - * Foo.prototype.c = 3; + * @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. `===`. * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - var toPairsIn = createToPairs(keysIn); + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } /** - * 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`. + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. * - * @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 + * @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`. * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] + * 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. * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); + 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); - 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 = {}; - } + 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]; } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } + // 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; - /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @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 - * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); + return data; } /** - * 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). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @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 - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; } /** - * 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). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @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 = {}; + * Converts `value` to a string using `Object.prototype.toString`. * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + function objectToString(value) { + return nativeObjectToString.call(value); } /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) + * A specialized version of `baseRest` which transforms the rest array. * - * _.values('hi'); - * // => ['h', 'i'] + * @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 values(object) { - return object == null ? [] : baseValues(object, keys(object)); + 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); + }; } /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * Gets the parent value at `path` of `object`. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object + * @private * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } - /*------------------------------------------------------------------------*/ - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. - * - * @static - * @memberOf _ - * @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 - * - * _.clamp(-10, -5, 5); - * // => -5 + * 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. * - * _.clamp(10, -5, 5); - * // => 5 + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. */ - 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; + 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 baseClamp(toNumber(number), lower, upper); + return array; } /** - * 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 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 - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * - * _.inRange(-3, -2, -6); - * // => true + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; } - number = toNumber(number); - return baseInRange(number, start, end); + + if (key == '__proto__') { + return; + } + + return object[key]; } /** - * 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.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 - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 + * Sets metadata for `func`. * - * _.random(5, true); - * // => a floating-point number between 0 and 5 + * **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. * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - 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); - } - - /*------------------------------------------------------------------------*/ + var setData = shortOut(baseSetData); /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' + * @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 camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example + * Sets the `toString` method of `func` to return `string`. * - * _.capitalize('FRED'); - * // => 'Fred' + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } + var setToString = shortOut(baseSetToString); /** - * 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 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example + * 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. * - * _.deburr('déjà vu'); - * // => 'deja vu' + * @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 deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** - * 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 - * - * _.endsWith('abc', 'b'); - * // => false + * 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. * - * _.endsWith('abc', 'b', 2); - * // => true + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); + function shortOut(func) { + var count = 0, + lastCalled = 0; - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; } /** - * 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 _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; + 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; } /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * Converts `string` to a property path array. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' + * Converts `func` to its source code. * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } /** - * Converts `string`, as space separated words, to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. - * @example - * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' + * Updates wrapper `details` based on `bitmask` flags. * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); + 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(); + } /** - * Converts the first character of `string` to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.lowerFirst('Fred'); - * // => 'fred' + * Creates a clone of `wrapper`. * - * _.lowerFirst('FRED'); - * // => 'fRED' + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. */ - var lowerFirst = createCaseFirst('toLowerCase'); + 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; + } + + /*------------------------------------------------------------------------*/ /** - * 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`. + * 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. * * @static * @memberOf _ * @since 3.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. + * @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. * @example * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] * - * _.pad('abc', 3); - * // => 'abc' + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); + 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)); - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); + return result; } /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ - * @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. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padEnd('abc', 3); - * // => 'abc' + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; } /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * Creates a new array concatenating `array` with any additional arrays + * and/or values. * * @static * @memberOf _ * @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. + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. * @example * - * _.padStart('abc', 6); - * // => ' abc' + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' + * console.log(other); + * // => [1, 2, 3, [4]] * - * _.padStart('abc', 3); - * // => 'abc' + * console.log(array); + * // => [1] */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. + * 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:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. + * @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 * @example * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] + * _.difference([2, 1], [2, 3]); + * // => [1] */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); /** - * Repeats the given string `n` times. + * 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 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. + * @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 * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] * - * _.repeat('abc', 0); - * // => '' + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; } - return baseRepeat(toString(string), n); - } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); /** - * Replaces matches for `pattern` in `string` with `replacement`. + * 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:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @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. + * @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. * @example * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); - } + 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) + : []; + }); /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. + * @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 * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' - */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); - - /** - * Splits `string` by `separator`. + * _.drop([1, 2, 3]); + * // => [2, 3] * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). + * _.drop([1, 2, 3], 2); + * // => [3] * - * @static - * @memberOf _ - * @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 + * _.drop([1, 2, 3], 5); + * // => [] * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] */ - 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) { + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { 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); + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. + * @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 * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' + * _.dropRight([1, 2, 3]); + * // => [1, 2] * - * _.startCase('fooBar'); - * // => 'Foo Bar' + * _.dropRight([1, 2, 3], 2); + * // => [1] * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); + 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); + } /** - * Checks if `string` starts with the given target string. + * 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 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`. + * @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 * - * _.startsWith('abc', 'a'); - * // => true + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * _.startsWith('abc', 'b'); - * // => false + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] * - * _.startsWith('abc', 'b', 1); - * // => true + * // 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 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; + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; } /** - * 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. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * 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). + * 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). * * @static - * @since 0.1.0 * @memberOf _ - * @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. + * @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 * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': '