From d762b77cc2977379a93a9ee7b91bb3a8f6c02d86 Mon Sep 17 00:00:00 2001 From: Yuri Volkov <0@mcornholio.ru> Date: Thu, 9 Jan 2025 10:25:32 +0100 Subject: [PATCH] Dependencies upgrade (#56) --- .github/workflows/check-dist.yml | 6 +- .github/workflows/ci.yml | 6 +- .github/workflows/create-pr.yml | 8 +- dist/37.index.js | 452 + dist/841.index.js | 6980 ++++ dist/index.js | 62366 +++++++++++++++-------------- package.json | 12 +- src/parse-RFC.ts | 2 - src/subsquare.ts | 5 +- yarn.lock | 2185 +- 10 files changed, 40004 insertions(+), 32018 deletions(-) create mode 100644 dist/37.index.js create mode 100644 dist/841.index.js diff --git a/.github/workflows/check-dist.yml b/.github/workflows/check-dist.yml index 6d8914f..0bdf216 100644 --- a/.github/workflows/check-dist.yml +++ b/.github/workflows/check-dist.yml @@ -30,12 +30,12 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup Node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: yarn - name: Install Dependencies diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b9fa256..5394939 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,12 +14,12 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup Node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: yarn - name: Install Dependencies diff --git a/.github/workflows/create-pr.yml b/.github/workflows/create-pr.yml index 3eb2e71..b617eff 100644 --- a/.github/workflows/create-pr.yml +++ b/.github/workflows/create-pr.yml @@ -11,12 +11,12 @@ permissions: jobs: create-pr: - name: Create a test PR after merge + name: Create a test PR after merge runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 # We need a fresh base branch every time, # so that it doesn't contain the text that we want to merge with the PR. @@ -26,11 +26,11 @@ jobs: timestamp=$(date +%Y-%m-%dT%H-%M) echo "base_branch=test_base_$timestamp" >> $GITHUB_OUTPUT echo "head_branch=test_head_$timestamp" >> $GITHUB_OUTPUT - + - name: Create a base branch run: | git push origin HEAD:${{ steps.generate_branches.outputs.base_branch }} - + - name: Create the changes for the PR run: | mkdir text diff --git a/dist/37.index.js b/dist/37.index.js new file mode 100644 index 0000000..a7e3f8a --- /dev/null +++ b/dist/37.index.js @@ -0,0 +1,452 @@ +"use strict"; +exports.id = 37; +exports.ids = [37]; +exports.modules = { + +/***/ 94037: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "toFormData": () => (/* binding */ toFormData) +/* harmony export */ }); +/* harmony import */ var fetch_blob_from_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52185); +/* harmony import */ var formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(68010); + + + +let s = 0; +const 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++, + END: s++ +}; + +let f = 1; +const F = { + PART_BOUNDARY: f, + LAST_BOUNDARY: f *= 2 +}; + +const LF = 10; +const CR = 13; +const SPACE = 32; +const HYPHEN = 45; +const COLON = 58; +const A = 97; +const Z = 122; + +const lower = c => c | 0x20; + +const noop = () => {}; + +class MultipartParser { + /** + * @param {string} boundary + */ + constructor(boundary) { + this.index = 0; + this.flags = 0; + + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + + this.boundaryChars = {}; + + boundary = '\r\n--' + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i = 0; i < boundary.length; i++) { + ui8a[i] = boundary.charCodeAt(i); + this.boundaryChars[ui8a[i]] = true; + } + + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + + /** + * @param {Uint8Array} data + */ + write(data) { + let i = 0; + const length_ = data.length; + let previousIndex = this.index; + let {lookbehind, boundary, boundaryChars, index, state, flags} = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + + const mark = name => { + this[name + 'Mark'] = i; + }; + + const clear = name => { + delete this[name + 'Mark']; + }; + + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === undefined || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + + const dataCallback = (name, clear) => { + const markSymbol = name + 'Mark'; + if (!(markSymbol in this)) { + return; + } + + if (clear) { + callback(name, this[markSymbol], i, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + + for (i = 0; i < length_; i++) { + c = data[i]; + + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + } else { + return; + } + + break; + } + + if (c !== boundary[index + 2]) { + index = -2; + } + + if (c === boundary[index + 2]) { + index++; + } + + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark('onHeaderField'); + index = 0; + // falls through + case S.HEADER_FIELD: + if (c === CR) { + clear('onHeaderField'); + state = S.HEADERS_ALMOST_DONE; + break; + } + + index++; + if (c === HYPHEN) { + break; + } + + if (c === COLON) { + if (index === 1) { + // empty header field + return; + } + + dataCallback('onHeaderField', true); + state = S.HEADER_VALUE_START; + break; + } + + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + + mark('onHeaderValue'); + state = S.HEADER_VALUE; + // falls through + case S.HEADER_VALUE: + if (c === CR) { + dataCallback('onHeaderValue', true); + callback('onHeaderEnd'); + state = S.HEADER_VALUE_ALMOST_DONE; + } + + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + + callback('onHeadersEnd'); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark('onPartData'); + // falls through + case S.PART_DATA: + previousIndex = index; + + if (index === 0) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while (i < bufferLength && !(data[i] in boundaryChars)) { + i += boundaryLength; + } + + i -= boundaryEnd; + c = data[i]; + } + + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback('onPartData', 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('onPartEnd'); + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback('onPartEnd'); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + + 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 (previousIndex > 0) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback('onPartData', 0, previousIndex, _lookbehind); + previousIndex = 0; + mark('onPartData'); + + // 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: + throw new Error(`Unexpected state entered: ${state}`); + } + } + + dataCallback('onHeaderField'); + dataCallback('onHeaderValue'); + dataCallback('onPartData'); + + // Update properties for the next call + this.index = index; + this.state = state; + this.flags = flags; + } + + end() { + if ((this.state === S.HEADER_FIELD_START && this.index === 0) || + (this.state === S.PART_DATA && this.index === this.boundary.length)) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error('MultipartParser.end(): stream ended unexpectedly'); + } + } +} + +function _fileName(headerValue) { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m) { + return; + } + + const match = m[2] || m[3] || ''; + let filename = match.slice(match.lastIndexOf('\\') + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m, code) => { + return String.fromCharCode(code); + }); + return filename; +} + +async function toFormData(Body, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError('Failed to fetch'); + } + + const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + + if (!m) { + throw new TypeError('no or bad content-type header, no multipart boundary'); + } + + const parser = new MultipartParser(m[1] || m[2]); + + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_1__/* .FormData */ .Ct(); + + const onPartData = ui8a => { + entryValue += decoder.decode(ui8a, {stream: true}); + }; + + const appendToFile = ui8a => { + entryChunks.push(ui8a); + }; + + const appendFileToFormData = () => { + const file = new fetch_blob_from_js__WEBPACK_IMPORTED_MODULE_0__/* .File */ .$B(entryChunks, filename, {type: contentType}); + formData.append(entryName, file); + }; + + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + + const decoder = new TextDecoder('utf-8'); + decoder.decode(); + + parser.onPartBegin = function () { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + + headerField = ''; + headerValue = ''; + entryValue = ''; + entryName = ''; + contentType = ''; + filename = null; + entryChunks.length = 0; + }; + + parser.onHeaderField = function (ui8a) { + headerField += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderValue = function (ui8a) { + headerValue += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderEnd = function () { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + + if (headerField === 'content-disposition') { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + const m = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + + if (m) { + entryName = m[2] || m[3] || ''; + } + + filename = _fileName(headerValue); + + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === 'content-type') { + contentType = headerValue; + } + + headerValue = ''; + headerField = ''; + }; + + for await (const chunk of Body) { + parser.write(chunk); + } + + parser.end(); + + return formData; +} + + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/841.index.js b/dist/841.index.js new file mode 100644 index 0000000..a8bbbed --- /dev/null +++ b/dist/841.index.js @@ -0,0 +1,6980 @@ +exports.id = 841; +exports.ids = [841]; +exports.modules = { + +/***/ 97760: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = __webpack_require__(71267), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +/***/ }), + +/***/ 21452: +/***/ (function(__unused_webpack_module, exports) { + +/** + * web-streams-polyfill v3.2.1 + */ +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + /// + function noop() { + return undefined; + } + function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + // Not implemented correctly + function TransferArrayBuffer(O) { + return O; + } + // Not implemented correctly + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line no-redeclare + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=ponyfill.es2018.js.map + + +/***/ }), + +/***/ 18572: +/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + +/* c8 ignore start */ +// 64 KiB (same size chrome slice theirs blob into Uint8array's) +const POOL_SIZE = 65536 + +if (!globalThis.ReadableStream) { + // `node:stream/web` got introduced in v16.5.0 as experimental + // and it's preferred over the polyfilled version. So we also + // suppress the warning that gets emitted by NodeJS for using it. + try { + const process = __webpack_require__(97742) + const { emitWarning } = process + try { + process.emitWarning = () => {} + Object.assign(globalThis, __webpack_require__(72477)) + process.emitWarning = emitWarning + } catch (error) { + process.emitWarning = emitWarning + throw error + } + } catch (error) { + // fallback to polyfill implementation + Object.assign(globalThis, __webpack_require__(21452)) + } +} + +try { + // Don't use node: prefix for this, require+node: is not supported until node v14.14 + // Only `import()` can use prefix in 12.20 and later + const { Blob } = __webpack_require__(14300) + if (Blob && !Blob.prototype.stream) { + Blob.prototype.stream = function name (params) { + let position = 0 + const blob = this + + return new ReadableStream({ + type: 'bytes', + async pull (ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE)) + const buffer = await chunk.arrayBuffer() + position += buffer.byteLength + ctrl.enqueue(new Uint8Array(buffer)) + + if (position === blob.size) { + ctrl.close() + } + } + }) + } + } +} catch (error) {} +/* c8 ignore end */ + + +/***/ }), + +/***/ 93213: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* unused harmony export File */ +/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11410); + + +const _File = class File extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z { + #lastModified = 0 + #name = '' + + /** + * @param {*[]} fileBits + * @param {string} fileName + * @param {{lastModified?: number, type?: string}} options + */// @ts-ignore + constructor (fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`) + } + super(fileBits, options) + + if (options === null) options = {} + + // Simulate WebIDL type casting for NaN value in lastModified option. + const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified) + if (!Number.isNaN(lastModified)) { + this.#lastModified = lastModified + } + + this.#name = String(fileName) + } + + get name () { + return this.#name + } + + get lastModified () { + return this.#lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } + + static [Symbol.hasInstance] (object) { + return !!object && object instanceof _index_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z && + /^(File)$/.test(object[Symbol.toStringTag]) + } +} + +/** @type {typeof globalThis.File} */// @ts-ignore +const File = _File +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (File); + + +/***/ }), + +/***/ 52185: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "$B": () => (/* reexport safe */ _file_js__WEBPACK_IMPORTED_MODULE_3__.Z), +/* harmony export */ "RA": () => (/* binding */ fileFromSync), +/* harmony export */ "SX": () => (/* binding */ blobFromSync), +/* harmony export */ "e2": () => (/* binding */ fileFrom), +/* harmony export */ "t6": () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_4__.Z), +/* harmony export */ "xB": () => (/* binding */ blobFrom) +/* harmony export */ }); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(87561); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49411); +/* harmony import */ var node_domexception__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97760); +/* harmony import */ var _file_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(93213); +/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11410); + + + + + + + +const { stat } = node_fs__WEBPACK_IMPORTED_MODULE_0__.promises + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +const blobFromSync = (path, type) => fromBlob((0,node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync)(path), path, type) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +const blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type)) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +const fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type)) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +const fileFromSync = (path, type) => fromFile((0,node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync)(path), path, type) + +// @ts-ignore +const fromBlob = (stat, path, type = '') => new _index_js__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .Z([new BlobDataItem({ + path, + size: stat.size, + lastModified: stat.mtimeMs, + start: 0 +})], { type }) + +// @ts-ignore +const fromFile = (stat, path, type = '') => new _file_js__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .Z([new BlobDataItem({ + path, + size: stat.size, + lastModified: stat.mtimeMs, + start: 0 +})], (0,node_path__WEBPACK_IMPORTED_MODULE_1__.basename)(path), { type, lastModified: stat.mtimeMs }) + +/** + * This is a blob backed up by a file on the disk + * with minium requirement. Its wrapped around a Blob as a blobPart + * so you have no direct access to this. + * + * @private + */ +class BlobDataItem { + #path + #start + + constructor (options) { + this.#path = options.path + this.#start = options.start + this.size = options.size + this.lastModified = options.lastModified + } + + /** + * Slicing arguments is first validated and formatted + * to not be out of range by Blob.prototype.slice + */ + slice (start, end) { + return new BlobDataItem({ + path: this.#path, + lastModified: this.lastModified, + size: end - start, + start: this.#start + start + }) + } + + async * stream () { + const { mtimeMs } = await stat(this.#path) + if (mtimeMs > this.lastModified) { + throw new node_domexception__WEBPACK_IMPORTED_MODULE_2__('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError') + } + yield * (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.createReadStream)(this.#path, { + start: this.#start, + end: this.#start + this.size - 1 + }) + } + + get [Symbol.toStringTag] () { + return 'Blob' + } +} + +/* unused harmony default export */ var __WEBPACK_DEFAULT_EXPORT__ = ((/* unused pure expression or super */ null && (blobFromSync))); + + + +/***/ }), + +/***/ 11410: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* unused harmony export Blob */ +/* harmony import */ var _streams_cjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18572); +/*! fetch-blob. MIT License. Jimmy Wärting */ + +// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x) +// Node has recently added whatwg stream into core + + + +// 64 KiB (same size chrome slice theirs blob into Uint8array's) +const POOL_SIZE = 65536 + +/** @param {(Blob | Uint8Array)[]} parts */ +async function * toIterator (parts, clone = true) { + for (const part of parts) { + if ('stream' in part) { + yield * (/** @type {AsyncIterableIterator} */ (part.stream())) + } else if (ArrayBuffer.isView(part)) { + if (clone) { + let position = part.byteOffset + const end = part.byteOffset + part.byteLength + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE) + const chunk = part.buffer.slice(position, position + size) + position += chunk.byteLength + yield new Uint8Array(chunk) + } + } else { + yield part + } + /* c8 ignore next 10 */ + } else { + // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob) + let position = 0, b = (/** @type {Blob} */ (part)) + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)) + const buffer = await chunk.arrayBuffer() + position += buffer.byteLength + yield new Uint8Array(buffer) + } + } + } +} + +const _Blob = class Blob { + /** @type {Array.<(Blob|Uint8Array)>} */ + #parts = [] + #type = '' + #size = 0 + #endings = 'transparent' + + /** + * The Blob() constructor returns a new Blob object. The content + * of the blob consists of the concatenation of the values given + * in the parameter array. + * + * @param {*} blobParts + * @param {{ type?: string, endings?: string }} [options] + */ + constructor (blobParts = [], options = {}) { + if (typeof blobParts !== 'object' || blobParts === null) { + throw new TypeError('Failed to construct \'Blob\': The provided value cannot be converted to a sequence.') + } + + if (typeof blobParts[Symbol.iterator] !== 'function') { + throw new TypeError('Failed to construct \'Blob\': The object must have a callable @@iterator property.') + } + + if (typeof options !== 'object' && typeof options !== 'function') { + throw new TypeError('Failed to construct \'Blob\': parameter 2 cannot convert to dictionary.') + } + + if (options === null) options = {} + + const encoder = new TextEncoder() + for (const element of blobParts) { + let part + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)) + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)) + } else if (element instanceof Blob) { + part = element + } else { + part = encoder.encode(`${element}`) + } + + this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size + this.#parts.push(part) + } + + this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}` + const type = options.type === undefined ? '' : String(options.type) + this.#type = /^[\x20-\x7E]*$/.test(type) ? type : '' + } + + /** + * The Blob interface's size property returns the + * size of the Blob in bytes. + */ + get size () { + return this.#size + } + + /** + * The type property of a Blob object returns the MIME type of the file. + */ + get type () { + return this.#type + } + + /** + * The text() method in the Blob interface returns a Promise + * that resolves with a string containing the contents of + * the blob, interpreted as UTF-8. + * + * @return {Promise} + */ + async text () { + // More optimized than using this.arrayBuffer() + // that requires twice as much ram + const decoder = new TextDecoder() + let str = '' + for await (const part of toIterator(this.#parts, false)) { + str += decoder.decode(part, { stream: true }) + } + // Remaining + str += decoder.decode() + return str + } + + /** + * The arrayBuffer() method in the Blob interface returns a + * Promise that resolves with the contents of the blob as + * binary data contained in an ArrayBuffer. + * + * @return {Promise} + */ + async arrayBuffer () { + // Easier way... Just a unnecessary overhead + // const view = new Uint8Array(this.size); + // await this.stream().getReader({mode: 'byob'}).read(view); + // return view.buffer; + + const data = new Uint8Array(this.size) + let offset = 0 + for await (const chunk of toIterator(this.#parts, false)) { + data.set(chunk, offset) + offset += chunk.length + } + + return data.buffer + } + + stream () { + const it = toIterator(this.#parts, true) + + return new globalThis.ReadableStream({ + // @ts-ignore + type: 'bytes', + async pull (ctrl) { + const chunk = await it.next() + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value) + }, + + async cancel () { + await it.return() + } + }) + } + + /** + * The Blob interface's slice() method creates and returns a + * new Blob object which contains data from a subset of the + * blob on which it's called. + * + * @param {number} [start] + * @param {number} [end] + * @param {string} [type] + */ + slice (start = 0, end = this.size, type = '') { + const { size } = this + + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size) + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size) + + const span = Math.max(relativeEnd - relativeStart, 0) + const parts = this.#parts + const blobParts = [] + let added = 0 + + for (const part of parts) { + // don't add the overflow to new blobParts + if (added >= span) { + break + } + + const size = ArrayBuffer.isView(part) ? part.byteLength : part.size + if (relativeStart && size <= relativeStart) { + // Skip the beginning and change the relative + // start & end position as we skip the unwanted parts + relativeStart -= size + relativeEnd -= size + } else { + let chunk + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size, relativeEnd)) + added += chunk.byteLength + } else { + chunk = part.slice(relativeStart, Math.min(size, relativeEnd)) + added += chunk.size + } + relativeEnd -= size + blobParts.push(chunk) + relativeStart = 0 // All next sequential parts should start at 0 + } + } + + const blob = new Blob([], { type: String(type).toLowerCase() }) + blob.#size = span + blob.#parts = blobParts + + return blob + } + + get [Symbol.toStringTag] () { + return 'Blob' + } + + static [Symbol.hasInstance] (object) { + return ( + object && + typeof object === 'object' && + typeof object.constructor === 'function' && + ( + typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function' + ) && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) + } +} + +Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}) + +/** @type {typeof globalThis.Blob} */ +const Blob = _Blob +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Blob); + + +/***/ }), + +/***/ 68010: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Ct": () => (/* binding */ FormData), +/* harmony export */ "au": () => (/* binding */ formDataToBlob) +/* harmony export */ }); +/* unused harmony export File */ +/* harmony import */ var fetch_blob__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11410); +/* harmony import */ var fetch_blob_file_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(93213); +/*! formdata-polyfill. MIT License. Jimmy Wärting */ + + + + +var {toStringTag:t,iterator:i,hasInstance:h}=Symbol, +r=Math.random, +m='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','), +f=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new fetch_blob_file_js__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z([b],c,b):b]:[a,b+'']), +e=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'), +x=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')} +append(...a){x('append',arguments,2);this.#d.push(f(...a))} +delete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)} +get(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b} +has(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)} +forEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)} +set(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b} +*entries(){yield*this.#d} +*keys(){for(var[a]of this)yield a} +*values(){for(var[,a]of this)yield a}} + +/** @param {FormData} F */ +function formDataToBlob (F,B=fetch_blob__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z){ +var b=`${r()}${r()}`.replace(/\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\r\nContent-Disposition: form-data; name="` +F.forEach((v,n)=>typeof v=='string' +?c.push(p+e(n)+`"\r\n\r\n${v.replace(/\r(?!\n)|(? { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "AbortError": () => (/* reexport */ AbortError), + "Blob": () => (/* reexport */ from/* Blob */.t6), + "FetchError": () => (/* reexport */ FetchError), + "File": () => (/* reexport */ from/* File */.$B), + "FormData": () => (/* reexport */ esm_min/* FormData */.Ct), + "Headers": () => (/* reexport */ Headers), + "Request": () => (/* reexport */ Request), + "Response": () => (/* reexport */ Response), + "blobFrom": () => (/* reexport */ from/* blobFrom */.xB), + "blobFromSync": () => (/* reexport */ from/* blobFromSync */.SX), + "default": () => (/* binding */ fetch), + "fileFrom": () => (/* reexport */ from/* fileFrom */.e2), + "fileFromSync": () => (/* reexport */ from/* fileFromSync */.RA), + "isRedirect": () => (/* reexport */ isRedirect) +}); + +// EXTERNAL MODULE: external "node:http" +var external_node_http_ = __webpack_require__(88849); +// EXTERNAL MODULE: external "node:https" +var external_node_https_ = __webpack_require__(22286); +// EXTERNAL MODULE: external "node:zlib" +var external_node_zlib_ = __webpack_require__(65628); +// EXTERNAL MODULE: external "node:stream" +var external_node_stream_ = __webpack_require__(84492); +// EXTERNAL MODULE: external "node:buffer" +var external_node_buffer_ = __webpack_require__(72254); +;// CONCATENATED MODULE: ./node_modules/data-uri-to-buffer/dist/index.js +/** + * Returns a `Buffer` instance from the given data URI `uri`. + * + * @param {String} uri Data URI to turn into a Buffer instance + * @returns {Buffer} Buffer instance from Data URI + * @api public + */ +function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + // strip newlines + uri = uri.replace(/\r?\n/g, ''); + // split the URI up into the "metadata" and the "data" portions + const firstComma = uri.indexOf(','); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError('malformed data: URI'); + } + // remove the "data:" scheme and parse the metadata + const meta = uri.substring(5, firstComma).split(';'); + let charset = ''; + let base64 = false; + const type = meta[0] || 'text/plain'; + let typeFull = type; + for (let i = 1; i < meta.length; i++) { + if (meta[i] === 'base64') { + base64 = true; + } + else if (meta[i]) { + typeFull += `;${meta[i]}`; + if (meta[i].indexOf('charset=') === 0) { + charset = meta[i].substring(8); + } + } + } + // defaults to US-ASCII only if type is not provided + if (!meta[0] && !charset.length) { + typeFull += ';charset=US-ASCII'; + charset = 'US-ASCII'; + } + // get the encoded data portion and decode URI-encoded chars + const encoding = base64 ? 'base64' : 'ascii'; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + // set `.type` and `.typeFull` properties to MIME type + buffer.type = type; + buffer.typeFull = typeFull; + // set the `.charset` property + buffer.charset = charset; + return buffer; +} +/* harmony default export */ const dist = (dataUriToBuffer); +//# sourceMappingURL=index.js.map +// EXTERNAL MODULE: external "node:util" +var external_node_util_ = __webpack_require__(47261); +// EXTERNAL MODULE: ./node_modules/fetch-blob/index.js +var fetch_blob = __webpack_require__(11410); +// EXTERNAL MODULE: ./node_modules/formdata-polyfill/esm.min.js +var esm_min = __webpack_require__(68010); +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/errors/base.js +class FetchBaseError extends Error { + constructor(message, type) { + super(message); + // Hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); + + this.type = type; + } + + get name() { + return this.constructor.name; + } + + get [Symbol.toStringTag]() { + return this.constructor.name; + } +} + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/errors/fetch-error.js + + + +/** + * @typedef {{ address?: string, code: string, dest?: string, errno: number, info?: object, message: string, path?: string, port?: number, syscall: string}} SystemError +*/ + +/** + * FetchError interface for operational errors + */ +class FetchError extends FetchBaseError { + /** + * @param {string} message - Error message for human + * @param {string} [type] - Error type for machine + * @param {SystemError} [systemError] - For Node.js system error + */ + constructor(message, type, systemError) { + super(message, type); + // When err.type is `system`, err.erroredSysCall contains system error and err.code contains system error code + if (systemError) { + // eslint-disable-next-line no-multi-assign + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } +} + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/is.js +/** + * Is.js + * + * Object type checks. + */ + +const NAME = Symbol.toStringTag; + +/** + * Check if `obj` is a URLSearchParams object + * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143 + * @param {*} object - Object to check for + * @return {boolean} + */ +const isURLSearchParameters = object => { + return ( + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + typeof object.sort === 'function' && + object[NAME] === 'URLSearchParams' + ); +}; + +/** + * Check if `object` is a W3C `Blob` object (which `File` inherits from) + * @param {*} object - Object to check for + * @return {boolean} + */ +const isBlob = object => { + return ( + object && + typeof object === 'object' && + typeof object.arrayBuffer === 'function' && + typeof object.type === 'string' && + typeof object.stream === 'function' && + typeof object.constructor === 'function' && + /^(Blob|File)$/.test(object[NAME]) + ); +}; + +/** + * Check if `obj` is an instance of AbortSignal. + * @param {*} object - Object to check for + * @return {boolean} + */ +const isAbortSignal = object => { + return ( + typeof object === 'object' && ( + object[NAME] === 'AbortSignal' || + object[NAME] === 'EventTarget' + ) + ); +}; + +/** + * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of + * the parent domain. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + + return orig === dest || orig.endsWith(`.${dest}`); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + + return orig === dest; +}; + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/body.js + +/** + * Body.js + * + * Body interface provides common methods for Request and Response + */ + + + + + + + + + + + + +const pipeline = (0,external_node_util_.promisify)(external_node_stream_.pipeline); +const INTERNALS = Symbol('Body internals'); + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Body { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + + if (body === null) { + // Body is undefined or null + body = null; + } else if (isURLSearchParameters(body)) { + // Body is a URLSearchParams + body = external_node_buffer_.Buffer.from(body.toString()); + } else if (isBlob(body)) { + // Body is blob + } else if (external_node_buffer_.Buffer.isBuffer(body)) { + // Body is Buffer + } else if (external_node_util_.types.isAnyArrayBuffer(body)) { + // Body is ArrayBuffer + body = external_node_buffer_.Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // Body is ArrayBufferView + body = external_node_buffer_.Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof external_node_stream_) { + // Body is stream + } else if (body instanceof esm_min/* FormData */.Ct) { + // Body is FormData + body = (0,esm_min/* formDataToBlob */.au)(body); + boundary = body.type.split('=')[1]; + } else { + // None of the above + // coerce to string then buffer + body = external_node_buffer_.Buffer.from(String(body)); + } + + let stream = body; + + if (external_node_buffer_.Buffer.isBuffer(body)) { + stream = external_node_stream_.Readable.from(body); + } else if (isBlob(body)) { + stream = external_node_stream_.Readable.from(body.stream()); + } + + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + + if (body instanceof external_node_stream_) { + body.on('error', error_ => { + const error = error_ instanceof FetchBaseError ? + error_ : + new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_); + this[INTERNALS].error = error; + }); + } + } + + get body() { + return this[INTERNALS].stream; + } + + get bodyUsed() { + return this[INTERNALS].disturbed; + } + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + async arrayBuffer() { + const {buffer, byteOffset, byteLength} = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + + async formData() { + const ct = this.headers.get('content-type'); + + if (ct.startsWith('application/x-www-form-urlencoded')) { + const formData = new esm_min/* FormData */.Ct(); + const parameters = new URLSearchParams(await this.text()); + + for (const [name, value] of parameters) { + formData.append(name, value); + } + + return formData; + } + + const {toFormData} = await __webpack_require__.e(/* import() */ 37).then(__webpack_require__.bind(__webpack_require__, 94037)); + return toFormData(this.body, ct); + } + + /** + * Return raw response as Blob + * + * @return Promise + */ + async blob() { + const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || ''; + const buf = await this.arrayBuffer(); + + return new fetch_blob/* default */.Z([buf], { + type: ct + }); + } + + /** + * Decode response as json + * + * @return Promise + */ + async json() { + const text = await this.text(); + return JSON.parse(text); + } + + /** + * Decode response as text + * + * @return Promise + */ + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody(this); + } +} + +Body.prototype.buffer = (0,external_node_util_.deprecate)(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer'); + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: {enumerable: true}, + bodyUsed: {enumerable: true}, + arrayBuffer: {enumerable: true}, + blob: {enumerable: true}, + json: {enumerable: true}, + text: {enumerable: true}, + data: {get: (0,external_node_util_.deprecate)(() => {}, + 'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead', + 'https://github.com/node-fetch/node-fetch/issues/1000 (response)')} +}); + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + + data[INTERNALS].disturbed = true; + + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + + const {body} = data; + + // Body is null + if (body === null) { + return external_node_buffer_.Buffer.alloc(0); + } + + /* c8 ignore next 3 */ + if (!(body instanceof external_node_stream_)) { + return external_node_buffer_.Buffer.alloc(0); + } + + // Body is stream + // get ready to actually consume the body + const accum = []; + let accumBytes = 0; + + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size'); + body.destroy(error); + throw error; + } + + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error); + throw error_; + } + + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every(c => typeof c === 'string')) { + return external_node_buffer_.Buffer.from(accum.join('')); + } + + return external_node_buffer_.Buffer.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} + +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @param String highWaterMark highWaterMark for both PassThrough body streams + * @return Mixed + */ +const clone = (instance, highWaterMark) => { + let p1; + let p2; + let {body} = instance[INTERNALS]; + + // Don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } + + // Check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if ((body instanceof external_node_stream_) && (typeof body.getBoundary !== 'function')) { + // Tee instance body + p1 = new external_node_stream_.PassThrough({highWaterMark}); + p2 = new external_node_stream_.PassThrough({highWaterMark}); + body.pipe(p1); + body.pipe(p2); + // Set instance body to teed body and return the other teed body + instance[INTERNALS].stream = p1; + body = p2; + } + + return body; +}; + +const getNonSpecFormDataBoundary = (0,external_node_util_.deprecate)( + body => body.getBoundary(), + 'form-data doesn\'t follow the spec and requires special treatment. Use alternative package', + 'https://github.com/node-fetch/node-fetch/issues/1167' +); + +/** + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param {any} body Any options.body input + * @returns {string | null} + */ +const extractContentType = (body, request) => { + // Body is null or undefined + if (body === null) { + return null; + } + + // Body is string + if (typeof body === 'string') { + return 'text/plain;charset=UTF-8'; + } + + // Body is a URLSearchParams + if (isURLSearchParameters(body)) { + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } + + // Body is blob + if (isBlob(body)) { + return body.type || null; + } + + // Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView) + if (external_node_buffer_.Buffer.isBuffer(body) || external_node_util_.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + + if (body instanceof esm_min/* FormData */.Ct) { + return `multipart/form-data; boundary=${request[INTERNALS].boundary}`; + } + + // Detect form data input from form-data module + if (body && typeof body.getBoundary === 'function') { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + + // Body is stream - can't really do much about this + if (body instanceof external_node_stream_) { + return null; + } + + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; +}; + +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. + * + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * + * @param {any} obj.body Body object from the Body instance. + * @returns {number | null} + */ +const getTotalBytes = request => { + const {body} = request[INTERNALS]; + + // Body is null or undefined + if (body === null) { + return 0; + } + + // Body is Blob + if (isBlob(body)) { + return body.size; + } + + // Body is Buffer + if (external_node_buffer_.Buffer.isBuffer(body)) { + return body.length; + } + + // Detect form data input from form-data module + if (body && typeof body.getLengthSync === 'function') { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + + // Body is stream + return null; +}; + +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param {Stream.Writable} dest The stream to write to. + * @param obj.body Body object from the Body instance. + * @returns {Promise} + */ +const writeToStream = async (dest, {body}) => { + if (body === null) { + // Body is null + dest.end(); + } else { + // Body is stream + await pipeline(body, dest); + } +}; + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/headers.js +/** + * Headers.js + * + * Headers class offers convenient helpers + */ + + + + +/* c8 ignore next 9 */ +const validateHeaderName = typeof external_node_http_.validateHeaderName === 'function' ? + external_node_http_.validateHeaderName : + name => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'}); + throw error; + } + }; + +/* c8 ignore next 9 */ +const validateHeaderValue = typeof external_node_http_.validateHeaderValue === 'function' ? + external_node_http_.validateHeaderValue : + (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'}); + throw error; + } + }; + +/** + * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit + */ + +/** + * This Fetch API interface allows you to perform various actions on HTTP request and response headers. + * These actions include retrieving, setting, adding to, and removing. + * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. + * You can add to this using methods like append() (see Examples.) + * In all methods of this interface, header names are matched by case-insensitive byte sequence. + * + */ +class Headers extends URLSearchParams { + /** + * Headers class + * + * @constructor + * @param {HeadersInit} [init] - Response headers + */ + constructor(init) { + // Validate and normalize init object in [name, value(s)][] + /** @type {string[][]} */ + let result = []; + if (init instanceof Headers) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map(value => [name, value])); + } + } else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq + // No op + } else if (typeof init === 'object' && !external_node_util_.types.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + // eslint-disable-next-line no-eq-null, eqeqeq + if (method == null) { + // Record + result.push(...Object.entries(init)); + } else { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // Sequence> + // Note: per spec we have to first exhaust the lists then process them + result = [...init] + .map(pair => { + if ( + typeof pair !== 'object' || external_node_util_.types.isBoxedPrimitive(pair) + ) { + throw new TypeError('Each header pair must be an iterable object'); + } + + return [...pair]; + }).map(pair => { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + + return [...pair]; + }); + } + } else { + throw new TypeError('Failed to construct \'Headers\': The provided value is not of type \'(sequence> or record)'); + } + + // Validate and lowercase + result = + result.length > 0 ? + result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : + undefined; + + super(result); + + // Returning a Proxy that will lowercase key names, validate parameters and sort keys + // eslint-disable-next-line no-constructor-return + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case 'append': + case 'set': + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase(), + String(value) + ); + }; + + case 'delete': + case 'has': + case 'getAll': + return name => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase() + ); + }; + + case 'keys': + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + + default: + return Reflect.get(target, p, receiver); + } + } + }); + /* c8 ignore next */ + } + + get [Symbol.toStringTag]() { + return this.constructor.name; + } + + toString() { + return Object.prototype.toString.call(this); + } + + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + + let value = values.join(', '); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + + return value; + } + + forEach(callback, thisArg = undefined) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + + * values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + + /** + * @type {() => IterableIterator<[string, string]>} + */ + * entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + + [Symbol.iterator]() { + return this.entries(); + } + + /** + * Node-fetch non-spec method + * returning all headers and their values as array + * @returns {Record} + */ + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + + /** + * For better console.log(headers) and also to convert Headers into Node.js Request compatible format + */ + [Symbol.for('nodejs.util.inspect.custom')]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + // Http.request() only supports string as Host header. + // This hack makes specifying custom Host header possible. + if (key === 'host') { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + + return result; + }, {}); + } +} + +/** + * Re-shaping object for Web IDL tests + * Only need to do it for overridden methods + */ +Object.defineProperties( + Headers.prototype, + ['get', 'entries', 'forEach', 'values'].reduce((result, property) => { + result[property] = {enumerable: true}; + return result; + }, {}) +); + +/** + * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do + * not conform to HTTP grammar productions. + * @param {import('http').IncomingMessage['rawHeaders']} headers + */ +function fromRawHeaders(headers = []) { + return new Headers( + headers + // Split into pairs + .reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + + return result; + }, []) + .filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; + } + }) + + ); +} + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/is-redirect.js +const redirectStatus = new Set([301, 302, 303, 307, 308]); + +/** + * Redirect code matching + * + * @param {number} code - Status code + * @return {boolean} + */ +const isRedirect = code => { + return redirectStatus.has(code); +}; + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/response.js +/** + * Response.js + * + * Response class provides content decoding + */ + + + + + +const response_INTERNALS = Symbol('Response internals'); + +/** + * Response class + * + * Ref: https://fetch.spec.whatwg.org/#response-class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response extends Body { + constructor(body = null, options = {}) { + super(body, options); + + // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition + const status = options.status != null ? options.status : 200; + + const headers = new Headers(options.headers); + + if (body !== null && !headers.has('Content-Type')) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[response_INTERNALS] = { + type: 'default', + url: options.url, + status, + statusText: options.statusText || '', + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + + get type() { + return this[response_INTERNALS].type; + } + + get url() { + return this[response_INTERNALS].url || ''; + } + + get status() { + return this[response_INTERNALS].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[response_INTERNALS].status >= 200 && this[response_INTERNALS].status < 300; + } + + get redirected() { + return this[response_INTERNALS].counter > 0; + } + + get statusText() { + return this[response_INTERNALS].statusText; + } + + get headers() { + return this[response_INTERNALS].headers; + } + + get highWaterMark() { + return this[response_INTERNALS].highWaterMark; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + + /** + * @param {string} url The URL that the new response is to originate from. + * @param {number} status An optional status code for the response (e.g., 302.) + * @returns {Response} A Response object. + */ + static redirect(url, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + + return new Response(null, { + headers: { + location: new URL(url).toString() + }, + status + }); + } + + static error() { + const response = new Response(null, {status: 0, statusText: ''}); + response[response_INTERNALS].type = 'error'; + return response; + } + + static json(data = undefined, init = {}) { + const body = JSON.stringify(data); + + if (body === undefined) { + throw new TypeError('data is not JSON serializable'); + } + + const headers = new Headers(init && init.headers); + + if (!headers.has('content-type')) { + headers.set('content-type', 'application/json'); + } + + return new Response(body, { + ...init, + headers + }); + } + + get [Symbol.toStringTag]() { + return 'Response'; + } +} + +Object.defineProperties(Response.prototype, { + type: {enumerable: true}, + url: {enumerable: true}, + status: {enumerable: true}, + ok: {enumerable: true}, + redirected: {enumerable: true}, + statusText: {enumerable: true}, + headers: {enumerable: true}, + clone: {enumerable: true} +}); + +// EXTERNAL MODULE: external "node:url" +var external_node_url_ = __webpack_require__(41041); +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/get-search.js +const getSearch = parsedURL => { + if (parsedURL.search) { + return parsedURL.search; + } + + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : ''); + return parsedURL.href[lastOffset - hash.length] === '?' ? '?' : ''; +}; + +// EXTERNAL MODULE: external "node:net" +var external_node_net_ = __webpack_require__(87503); +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/referrer.js + + +/** + * @external URL + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL} + */ + +/** + * @module utils/referrer + * @private + */ + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer} + * @param {string} URL + * @param {boolean} [originOnly=false] + */ +function stripURLForUseAsAReferrer(url, originOnly = false) { + // 1. If url is null, return no referrer. + if (url == null) { // eslint-disable-line no-eq-null, eqeqeq + return 'no-referrer'; + } + + url = new URL(url); + + // 2. If url's scheme is a local scheme, then return no referrer. + if (/^(about|blob|data):$/.test(url.protocol)) { + return 'no-referrer'; + } + + // 3. Set url's username to the empty string. + url.username = ''; + + // 4. Set url's password to null. + // Note: `null` appears to be a mistake as this actually results in the password being `"null"`. + url.password = ''; + + // 5. Set url's fragment to null. + // Note: `null` appears to be a mistake as this actually results in the fragment being `"#null"`. + url.hash = ''; + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 6.1. Set url's path to null. + // Note: `null` appears to be a mistake as this actually results in the path being `"/null"`. + url.pathname = ''; + + // 6.2. Set url's query to null. + // Note: `null` appears to be a mistake as this actually results in the query being `"?null"`. + url.search = ''; + } + + // 7. Return url. + return url; +} + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy} + */ +const ReferrerPolicy = new Set([ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +]); + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy} + */ +const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'; + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies} + * @param {string} referrerPolicy + * @returns {string} referrerPolicy + */ +function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + + return referrerPolicy; +} + +/** + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?} + * @param {external:URL} url + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" + */ +function isOriginPotentiallyTrustworthy(url) { + // 1. If origin is an opaque origin, return "Not Trustworthy". + // Not applicable + + // 2. Assert: origin is a tuple origin. + // Not for implementations + + // 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy". + if (/^(http|ws)s:$/.test(url.protocol)) { + return true; + } + + // 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy". + const hostIp = url.host.replace(/(^\[)|(]$)/g, ''); + const hostIPVersion = (0,external_node_net_.isIP)(hostIp); + + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + + // 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy". + // We are returning FALSE here because we cannot ensure conformance to + // let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost) + if (url.host === 'localhost' || url.host.endsWith('.localhost')) { + return false; + } + + // 6. If origin's scheme component is file, return "Potentially Trustworthy". + if (url.protocol === 'file:') { + return true; + } + + // 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy". + // Not supported + + // 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy". + // Not supported + + // 9. Return "Not Trustworthy". + return false; +} + +/** + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?} + * @param {external:URL} url + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" + */ +function isUrlPotentiallyTrustworthy(url) { + // 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy". + if (/^about:(blank|srcdoc)$/.test(url)) { + return true; + } + + // 2. If url's scheme is "data", return "Potentially Trustworthy". + if (url.protocol === 'data:') { + return true; + } + + // Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were + // created. Therefore, blobs created in a trustworthy origin will themselves be potentially + // trustworthy. + if (/^(blob|filesystem):$/.test(url.protocol)) { + return true; + } + + // 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin. + return isOriginPotentiallyTrustworthy(url); +} + +/** + * Modifies the referrerURL to enforce any extra security policy considerations. + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 + * @callback module:utils/referrer~referrerURLCallback + * @param {external:URL} referrerURL + * @returns {external:URL} modified referrerURL + */ + +/** + * Modifies the referrerOrigin to enforce any extra security policy considerations. + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 + * @callback module:utils/referrer~referrerOriginCallback + * @param {external:URL} referrerOrigin + * @returns {external:URL} modified referrerOrigin + */ + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer} + * @param {Request} request + * @param {object} o + * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback + * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback + * @returns {external:URL} Request's referrer + */ +function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) { + // There are 2 notes in the specification about invalid pre-conditions. We return null, here, for + // these cases: + // > Note: If request's referrer is "no-referrer", Fetch will not call into this algorithm. + // > Note: If request's referrer policy is the empty string, Fetch will not call into this + // > algorithm. + if (request.referrer === 'no-referrer' || request.referrerPolicy === '') { + return null; + } + + // 1. Let policy be request's associated referrer policy. + const policy = request.referrerPolicy; + + // 2. Let environment be request's client. + // not applicable to node.js + + // 3. Switch on request's referrer: + if (request.referrer === 'about:client') { + return 'no-referrer'; + } + + // "a URL": Let referrerSource be request's referrer. + const referrerSource = request.referrer; + + // 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer. + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the + // origin-only flag set to true. + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + + // 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set + // referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + + // 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary + // policy considerations in the interests of minimizing data leakage. For example, the user + // agent could strip the URL down to an origin, modify its host, replace it with an empty + // string, etc. + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + + // 8.Execute the statements corresponding to the value of policy: + const currentURL = new URL(request.url); + + switch (policy) { + case 'no-referrer': + return 'no-referrer'; + + case 'origin': + return referrerOrigin; + + case 'unsafe-url': + return referrerURL; + + case 'strict-origin': + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 2. Return referrerOrigin. + return referrerOrigin.toString(); + + case 'strict-origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 3. Return referrerOrigin. + return referrerOrigin; + + case 'same-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // 2. Return no referrer. + return 'no-referrer'; + + case 'origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // Return referrerOrigin. + return referrerOrigin; + + case 'no-referrer-when-downgrade': + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 2. Return referrerURL. + return referrerURL; + + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header} + * @param {Headers} headers Response headers + * @returns {string} policy + */ +function parseReferrerPolicyFromHeader(headers) { + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` + // and response’s header list. + const policyTokens = (headers.get('referrer-policy') || '').split(/[,\s]+/); + + // 2. Let policy be the empty string. + let policy = ''; + + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty + // string, then set policy to token. + // Note: This algorithm loops over multiple policy values to allow deployment of new policy + // values with fallbacks for older user agents, as described in § 11.1 Unknown Policy Values. + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + + // 4. Return policy. + return policy; +} + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/request.js +/** + * Request.js + * + * Request class contains server only options + * + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. + */ + + + + + + + + + +const request_INTERNALS = Symbol('Request internals'); + +/** + * Check if `obj` is an instance of Request. + * + * @param {*} object + * @return {boolean} + */ +const isRequest = object => { + return ( + typeof object === 'object' && + typeof object[request_INTERNALS] === 'object' + ); +}; + +const doBadDataWarn = (0,external_node_util_.deprecate)(() => {}, + '.data is not a valid RequestInit property, use .body instead', + 'https://github.com/node-fetch/node-fetch/issues/1000 (request)'); + +/** + * Request class + * + * Ref: https://fetch.spec.whatwg.org/#request-class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request extends Body { + constructor(input, init = {}) { + let parsedURL; + + // Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245) + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + + if (parsedURL.username !== '' || parsedURL.password !== '') { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + + let method = init.method || input.method || 'GET'; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + + if (!isRequest(init) && 'data' in init) { + doBadDataWarn(); + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if ((init.body != null || (isRequest(input) && input.body !== null)) && + (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + const inputBody = init.body ? + init.body : + (isRequest(input) && input.body !== null ? + clone(input) : + null); + + super(inputBody, { + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody !== null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? + input.signal : + null; + if ('signal' in init) { + signal = init.signal; + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget'); + } + + // §5.4, Request constructor steps, step 15.1 + // eslint-disable-next-line no-eq-null, eqeqeq + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === '') { + // §5.4, Request constructor steps, step 15.2 + referrer = 'no-referrer'; + } else if (referrer) { + // §5.4, Request constructor steps, step 15.3.1, 15.3.2 + const parsedReferrer = new URL(referrer); + // §5.4, Request constructor steps, step 15.3.3, 15.3.4 + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer; + } else { + referrer = undefined; + } + + this[request_INTERNALS] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal, + referrer + }; + + // Node-fetch-only options + this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow; + this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + + // §5.4, Request constructor steps, step 16. + // Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ''; + } + + /** @returns {string} */ + get method() { + return this[request_INTERNALS].method; + } + + /** @returns {string} */ + get url() { + return (0,external_node_url_.format)(this[request_INTERNALS].parsedURL); + } + + /** @returns {Headers} */ + get headers() { + return this[request_INTERNALS].headers; + } + + get redirect() { + return this[request_INTERNALS].redirect; + } + + /** @returns {AbortSignal} */ + get signal() { + return this[request_INTERNALS].signal; + } + + // https://fetch.spec.whatwg.org/#dom-request-referrer + get referrer() { + if (this[request_INTERNALS].referrer === 'no-referrer') { + return ''; + } + + if (this[request_INTERNALS].referrer === 'client') { + return 'about:client'; + } + + if (this[request_INTERNALS].referrer) { + return this[request_INTERNALS].referrer.toString(); + } + + return undefined; + } + + get referrerPolicy() { + return this[request_INTERNALS].referrerPolicy; + } + + set referrerPolicy(referrerPolicy) { + this[request_INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } + + get [Symbol.toStringTag]() { + return 'Request'; + } +} + +Object.defineProperties(Request.prototype, { + method: {enumerable: true}, + url: {enumerable: true}, + headers: {enumerable: true}, + redirect: {enumerable: true}, + clone: {enumerable: true}, + signal: {enumerable: true}, + referrer: {enumerable: true}, + referrerPolicy: {enumerable: true} +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param {Request} request - A Request instance + * @return The options object to be passed to http.request + */ +const getNodeRequestOptions = request => { + const {parsedURL} = request[request_INTERNALS]; + const headers = new Headers(request[request_INTERNALS].headers); + + // Fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body === null && /^(post|put)$/i.test(request.method)) { + contentLengthValue = '0'; + } + + if (request.body !== null) { + const totalBytes = getTotalBytes(request); + // Set Content-Length if totalBytes is a number (that is not NaN) + if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // 4.1. Main fetch, step 2.6 + // > If request's referrer policy is the empty string, then set request's referrer policy to the + // > default referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + + // 4.1. Main fetch, step 2.7 + // > If request's referrer is not "no-referrer", set request's referrer to the result of invoking + // > determine request's referrer. + if (request.referrer && request.referrer !== 'no-referrer') { + request[request_INTERNALS].referrer = determineRequestsReferrer(request); + } else { + request[request_INTERNALS].referrer = 'no-referrer'; + } + + // 4.5. HTTP-network-or-cache fetch, step 6.9 + // > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized + // > and isomorphic encoded, to httpRequest's header list. + if (request[request_INTERNALS].referrer instanceof URL) { + headers.set('Referer', request.referrer); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip, deflate, br'); + } + + let {agent} = request; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + const search = getSearch(parsedURL); + + // Pass the full URL directly to request(), but overwrite the following + // options: + const options = { + // Overwrite search to retain trailing ? (issue #776) + path: parsedURL.pathname + search, + // The following options are not expressed in the URL + method: request.method, + headers: headers[Symbol.for('nodejs.util.inspect.custom')](), + insecureHTTPParser: request.insecureHTTPParser, + agent + }; + + return { + /** @type {URL} */ + parsedURL, + options + }; +}; + +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/errors/abort-error.js + + +/** + * AbortError interface for cancelled requests + */ +class AbortError extends FetchBaseError { + constructor(message, type = 'aborted') { + super(message, type); + } +} + +// EXTERNAL MODULE: ./node_modules/fetch-blob/from.js +var from = __webpack_require__(52185); +;// CONCATENATED MODULE: ./node_modules/node-fetch/src/index.js +/** + * Index.js + * + * a request API compatible with window.fetch + * + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. + */ + + + + + + + + + + + + + + + + + + + + + + + + +const supportedSchemas = new Set(['data:', 'http:', 'https:']); + +/** + * Fetch function + * + * @param {string | URL | import('./request').default} url - Absolute url or Request instance + * @param {*} [options_] - Fetch options + * @return {Promise} + */ +async function fetch(url, options_) { + return new Promise((resolve, reject) => { + // Build request object + const request = new Request(url, options_); + const {parsedURL, options} = getNodeRequestOptions(request); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, '')}" is not supported.`); + } + + if (parsedURL.protocol === 'data:') { + const data = dist(request.url); + const response = new Response(data, {headers: {'Content-Type': data.typeFull}}); + resolve(response); + return; + } + + // Wrap http.request into fetch + const send = (parsedURL.protocol === 'https:' ? external_node_https_ : external_node_http_).request; + const {signal} = request; + let response = null; + + const abort = () => { + const error = new AbortError('The operation was aborted.'); + reject(error); + if (request.body && request.body instanceof external_node_stream_.Readable) { + request.body.destroy(error); + } + + if (!response || !response.body) { + return; + } + + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = () => { + abort(); + finalize(); + }; + + // Send request + const request_ = send(parsedURL.toString(), options); + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener('abort', abortAndFinalize); + } + }; + + request_.on('error', error => { + reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error)); + finalize(); + }); + + fixResponseChunkedTransferBadEnding(request_, error => { + if (response && response.body) { + response.body.destroy(error); + } + }); + + /* c8 ignore next 18 */ + if (process.version < 'v14') { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + request_.on('socket', s => { + let endedWithEventsCount; + s.prependListener('end', () => { + endedWithEventsCount = s._eventsCount; + }); + s.prependListener('close', hadError => { + // if end happened before close but the socket didn't emit an error, do it now + if (response && endedWithEventsCount < s._eventsCount && !hadError) { + const error = new Error('Premature close'); + error.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', error); + } + }); + }); + } + + request_.on('response', response_ => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + + // HTTP fetch step 5 + if (isRedirect(response_.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request.url); + } catch { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // Nothing to do + break; + case 'follow': { + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOptions = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: clone(request), + signal: request.signal, + size: request.size, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy + }; + + // when forwarding sensitive headers like "Authorization", + // "WWW-Authenticate", and "Cookie" to untrusted targets, + // headers will be ignored when following a redirect to a domain + // that is not a subdomain match or exact match of the initial domain. + // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" + // will forward the sensitive headers, but a redirect to "bar.com" will not. + // headers will also be ignored when following a redirect to a domain using + // a different protocol. For example, a redirect from "https://foo.com" to "http://foo.com" + // will not forward the sensitive headers + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOptions.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (response_.statusCode !== 303 && request.body && options_.body instanceof external_node_stream_.Readable) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) { + requestOptions.method = 'GET'; + requestOptions.body = undefined; + requestOptions.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 14 + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + + default: + return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`)); + } + } + + // Prepare response + if (signal) { + response_.once('end', () => { + signal.removeEventListener('abort', abortAndFinalize); + }); + } + + let body = (0,external_node_stream_.pipeline)(response_, new external_node_stream_.PassThrough(), error => { + if (error) { + reject(error); + } + }); + // see https://github.com/nodejs/node/pull/29376 + /* c8 ignore next 3 */ + if (process.version < 'v12.10') { + response_.on('aborted', abortAndFinalize); + } + + const responseOptions = { + url: request.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request.size, + counter: request.counter, + highWaterMark: request.highWaterMark + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: external_node_zlib_.Z_SYNC_FLUSH, + finishFlush: external_node_zlib_.Z_SYNC_FLUSH + }; + + // For gzip + if (codings === 'gzip' || codings === 'x-gzip') { + body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createGunzip(zlibOptions), error => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For deflate + if (codings === 'deflate' || codings === 'x-deflate') { + // Handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = (0,external_node_stream_.pipeline)(response_, new external_node_stream_.PassThrough(), error => { + if (error) { + reject(error); + } + }); + raw.once('data', chunk => { + // See http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createInflate(), error => { + if (error) { + reject(error); + } + }); + } else { + body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createInflateRaw(), error => { + if (error) { + reject(error); + } + }); + } + + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once('end', () => { + // Some old IIS servers return zero-length OK deflate responses, so + // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903 + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + + // For br + if (codings === 'br') { + body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createBrotliDecompress(), error => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // Otherwise, use response as-is + response = new Response(body, responseOptions); + resolve(response); + }); + + // eslint-disable-next-line promise/prefer-await-to-then + writeToStream(request_, request).catch(reject); + }); +} + +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + const LAST_CHUNK = external_node_buffer_.Buffer.from('0\r\n\r\n'); + + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + + request.on('response', response => { + const {headers} = response; + isChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length']; + }); + + request.on('socket', socket => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error('Premature close'); + error.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(error); + } + }; + + const onData = buf => { + properLastChunkReceived = external_node_buffer_.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + + // Sometimes final 0-length chunk and end of message code are in separate packets + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = ( + external_node_buffer_.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && + external_node_buffer_.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0 + ); + } + + previousChunk = buf; + }; + + socket.prependListener('close', onSocketClose); + socket.on('data', onData); + + request.on('close', () => { + socket.removeListener('close', onSocketClose); + socket.removeListener('data', onData); + }); + }); +} + + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index f4d2304..22c939e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -10748,7 +10748,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var endpoint = __nccwpck_require__(59440); var universalUserAgent = __nccwpck_require__(45030); var isPlainObject = __nccwpck_require__(63287); -var nodeFetch = _interopDefault(__nccwpck_require__(80467)); +var nodeFetch = _interopDefault(__nccwpck_require__(81768)); var requestError = __nccwpck_require__(10537); const VERSION = "5.6.3"; @@ -10920,11781 +10920,12277 @@ exports.request = request; /***/ }), -/***/ 89891: -/***/ ((__unused_webpack_module, exports) => { +/***/ 81768: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; -/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0; -function assertNumber(n) { - if (!Number.isSafeInteger(n)) - throw new Error(`Wrong integer: ${n}`); -} -exports.assertNumber = assertNumber; -function chain(...args) { - const wrap = (a, b) => (c) => a(b(c)); - const encode = Array.from(args) - .reverse() - .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined); - const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined); - return { encode, decode }; -} -function alphabet(alphabet) { - return { - encode: (digits) => { - if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) - throw new Error('alphabet.encode input should be an array of numbers'); - return digits.map((i) => { - assertNumber(i); - if (i < 0 || i >= alphabet.length) - throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); - return alphabet[i]; - }); - }, - decode: (input) => { - if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) - throw new Error('alphabet.decode input should be array of strings'); - return input.map((letter) => { - if (typeof letter !== 'string') - throw new Error(`alphabet.decode: not string element=${letter}`); - const index = alphabet.indexOf(letter); - if (index === -1) - throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); - return index; - }); - }, - }; -} -function join(separator = '') { - if (typeof separator !== 'string') - throw new Error('join separator should be string'); - return { - encode: (from) => { - if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) - throw new Error('join.encode input should be array of strings'); - for (let i of from) - if (typeof i !== 'string') - throw new Error(`join.encode: non-string input=${i}`); - return from.join(separator); - }, - decode: (to) => { - if (typeof to !== 'string') - throw new Error('join.decode input should be string'); - return to.split(separator); - }, - }; -} -function padding(bits, chr = '=') { - assertNumber(bits); - if (typeof chr !== 'string') - throw new Error('padding chr should be string'); - return { - encode(data) { - if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) - throw new Error('padding.encode input should be array of strings'); - for (let i of data) - if (typeof i !== 'string') - throw new Error(`padding.encode: non-string input=${i}`); - while ((data.length * bits) % 8) - data.push(chr); - return data; - }, - decode(input) { - if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) - throw new Error('padding.encode input should be array of strings'); - for (let i of input) - if (typeof i !== 'string') - throw new Error(`padding.decode: non-string input=${i}`); - let end = input.length; - if ((end * bits) % 8) - throw new Error('Invalid padding: string should have whole number of bytes'); - for (; end > 0 && input[end - 1] === chr; end--) { - if (!(((end - 1) * bits) % 8)) - throw new Error('Invalid padding: string has too much padding'); - } - return input.slice(0, end); - }, - }; -} -function normalize(fn) { - if (typeof fn !== 'function') - throw new Error('normalize fn should be function'); - return { encode: (from) => from, decode: (to) => fn(to) }; -} -function convertRadix(data, from, to) { - if (from < 2) - throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); - if (to < 2) - throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); - if (!Array.isArray(data)) - throw new Error('convertRadix: data should be array'); - if (!data.length) - return []; - let pos = 0; - const res = []; - const digits = Array.from(data); - digits.forEach((d) => { - assertNumber(d); - if (d < 0 || d >= from) - throw new Error(`Wrong integer: ${d}`); - }); - while (true) { - let carry = 0; - let done = true; - for (let i = pos; i < digits.length; i++) { - const digit = digits[i]; - const digitBase = from * carry + digit; - if (!Number.isSafeInteger(digitBase) || - (from * carry) / from !== carry || - digitBase - digit !== from * carry) { - throw new Error('convertRadix: carry overflow'); - } - carry = digitBase % to; - digits[i] = Math.floor(digitBase / to); - if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase) - throw new Error('convertRadix: carry overflow'); - if (!done) - continue; - else if (!digits[i]) - pos = i; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i = 0; i < data.length - 1 && data[i] === 0; i++) - res.push(0); - return res.reverse(); -} -const gcd = (a, b) => (!b ? a : gcd(b, a % b)); -const radix2carry = (from, to) => from + (to - gcd(from, to)); -function convertRadix2(data, from, to, padding) { - if (!Array.isArray(data)) - throw new Error('convertRadix2: data should be array'); - if (from <= 0 || from > 32) - throw new Error(`convertRadix2: wrong from=${from}`); - if (to <= 0 || to > 32) - throw new Error(`convertRadix2: wrong to=${to}`); - if (radix2carry(from, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); - } - let carry = 0; - let pos = 0; - const mask = 2 ** to - 1; - const res = []; - for (const n of data) { - assertNumber(n); - if (n >= 2 ** from) - throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); - carry = (carry << from) | n; - if (pos + from > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); - pos += from; - for (; pos >= to; pos -= to) - res.push(((carry >> (pos - to)) & mask) >>> 0); - carry &= 2 ** pos - 1; - } - carry = (carry << (to - pos)) & mask; - if (!padding && pos >= from) - throw new Error('Excess padding'); - if (!padding && carry) - throw new Error(`Non-zero padding: ${carry}`); - if (padding && pos > 0) - res.push(carry >>> 0); - return res; -} -function radix(num) { - assertNumber(num); - return { - encode: (bytes) => { - if (!(bytes instanceof Uint8Array)) - throw new Error('radix.encode input should be Uint8Array'); - return convertRadix(Array.from(bytes), 2 ** 8, num); - }, - decode: (digits) => { - if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) - throw new Error('radix.decode input should be array of strings'); - return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); - }, - }; -} -function radix2(bits, revPadding = false) { - assertNumber(bits); - if (bits <= 0 || bits > 32) - throw new Error('radix2: bits should be in (0..32]'); - if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) - throw new Error('radix2: carry overflow'); - return { - encode: (bytes) => { - if (!(bytes instanceof Uint8Array)) - throw new Error('radix2.encode input should be Uint8Array'); - return convertRadix2(Array.from(bytes), 8, bits, !revPadding); - }, - decode: (digits) => { - if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) - throw new Error('radix2.decode input should be array of strings'); - return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); - }, - }; -} -function unsafeWrapper(fn) { - if (typeof fn !== 'function') - throw new Error('unsafeWrapper fn should be function'); - return function (...args) { - try { - return fn.apply(null, args); - } - catch (e) { } - }; -} -function checksum(len, fn) { - assertNumber(len); - if (typeof fn !== 'function') - throw new Error('checksum fn should be function'); - return { - encode(data) { - if (!(data instanceof Uint8Array)) - throw new Error('checksum.encode: input should be Uint8Array'); - const checksum = fn(data).slice(0, len); - const res = new Uint8Array(data.length + len); - res.set(data); - res.set(checksum, data.length); - return res; - }, - decode(data) { - if (!(data instanceof Uint8Array)) - throw new Error('checksum.decode: input should be Uint8Array'); - const payload = data.slice(0, -len); - const newChecksum = fn(payload).slice(0, len); - const oldChecksum = data.slice(-len); - for (let i = 0; i < len; i++) - if (newChecksum[i] !== oldChecksum[i]) - throw new Error('Invalid checksum'); - return payload; - }, - }; -} -exports.utils = { alphabet, chain, checksum, radix, radix2, join, padding }; -exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); -exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); -exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); -exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); -exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); -exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')); -const genBase58 = (abc) => chain(radix(58), alphabet(abc), join('')); -exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); -exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'); -exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'); -const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; -exports.base58xmr = { - encode(data) { - let res = ''; - for (let i = 0; i < data.length; i += 8) { - const block = data.subarray(i, i + 8); - res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); - } - return res; - }, - decode(str) { - let res = []; - for (let i = 0; i < str.length; i += 11) { - const slice = str.slice(i, i + 11); - const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); - const block = exports.base58.decode(slice); - for (let j = 0; j < block.length - blockLen; j++) { - if (block[j] !== 0) - throw new Error('base58xmr: wrong padding'); - } - res = res.concat(Array.from(block.slice(block.length - blockLen))); - } - return Uint8Array.from(res); - }, -}; -const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58); -exports.base58check = base58check; -const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); -const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; -function bech32Polymod(pre) { - const b = pre >> 25; - let chk = (pre & 0x1ffffff) << 5; - for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { - if (((b >> i) & 1) === 1) - chk ^= POLYMOD_GENERATORS[i]; - } - return chk; -} -function bechChecksum(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i = 0; i < len; i++) { - const c = prefix.charCodeAt(i); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod(chk) ^ (c >> 5); - } - chk = bech32Polymod(chk); - for (let i = 0; i < len; i++) - chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); - for (let v of words) - chk = bech32Polymod(chk) ^ v; - for (let i = 0; i < 6; i++) - chk = bech32Polymod(chk); - chk ^= encodingConst; - return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); -} -function genBech32(encoding) { - const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; - const _words = radix2(5); - const fromWords = _words.decode; - const toWords = _words.encode; - const fromWordsUnsafe = unsafeWrapper(fromWords); - function encode(prefix, words, limit = 90) { - if (typeof prefix !== 'string') - throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); - if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) - throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); - const actualLength = prefix.length + 7 + words.length; - if (limit !== false && actualLength > limit) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); - prefix = prefix.toLowerCase(); - return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; - } - function decode(str, limit = 90) { - if (typeof str !== 'string') - throw new Error(`bech32.decode input should be string, not ${typeof str}`); - if (str.length < 8 || (limit !== false && str.length > limit)) - throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); - const lowered = str.toLowerCase(); - if (str !== lowered && str !== str.toUpperCase()) - throw new Error(`String must be lowercase or uppercase`); - str = lowered; - const sepIndex = str.lastIndexOf('1'); - if (sepIndex === 0 || sepIndex === -1) - throw new Error(`Letter "1" must be present between prefix and data only`); - const prefix = str.slice(0, sepIndex); - const _words = str.slice(sepIndex + 1); - if (_words.length < 6) - throw new Error('Data must be at least 6 characters long'); - const words = BECH_ALPHABET.decode(_words).slice(0, -6); - const sum = bechChecksum(prefix, words, ENCODING_CONST); - if (!_words.endsWith(sum)) - throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); - return { prefix, words }; - } - const decodeUnsafe = unsafeWrapper(decode); - function decodeToBytes(str) { - const { prefix, words } = decode(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; -} -exports.bech32 = genBech32('bech32'); -exports.bech32m = genBech32('bech32m'); -exports.utf8 = { - encode: (data) => new TextDecoder().decode(data), - decode: (str) => new TextEncoder().encode(str), -}; -exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { - if (typeof s !== 'string' || s.length % 2) - throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); - return s.toLowerCase(); -})); -const CODERS = { - utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr -}; -const coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`; -const bytesToString = (type, bytes) => { - if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) - throw new TypeError(coderTypeError); - if (!(bytes instanceof Uint8Array)) - throw new TypeError('bytesToString() expects Uint8Array'); - return CODERS[type].encode(bytes); -}; -exports.bytesToString = bytesToString; -exports.str = exports.bytesToString; -const stringToBytes = (type, str) => { - if (!CODERS.hasOwnProperty(type)) - throw new TypeError(coderTypeError); - if (typeof str !== 'string') - throw new TypeError('stringToBytes() expects string'); - return CODERS[type].decode(str); -}; -exports.stringToBytes = stringToBytes; -exports.bytes = exports.stringToBytes; +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -/***/ }), +var Stream = _interopDefault(__nccwpck_require__(12781)); +var http = _interopDefault(__nccwpck_require__(13685)); +var Url = _interopDefault(__nccwpck_require__(57310)); +var whatwgUrl = _interopDefault(__nccwpck_require__(28665)); +var https = _interopDefault(__nccwpck_require__(95687)); +var zlib = _interopDefault(__nccwpck_require__(59796)); -/***/ 97425: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js -"use strict"; +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); -const Url = __nccwpck_require__(57310); +class Blob { + constructor() { + this[TYPE] = ''; -const Errors = __nccwpck_require__(91594); + const blobParts = arguments[0]; + const options = arguments[1]; + const buffers = []; + let size = 0; -const internals = { - minDomainSegments: 2, - nonAsciiRx: /[^\x00-\x7f]/, - domainControlRx: /[\x00-\x20@\:\/\\#!\$&\'\(\)\*\+,;=\?]/, // Control + space + separators - tldSegmentRx: /^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, - domainSegmentRx: /^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, - URL: Url.URL || URL // $lab:coverage:ignore$ -}; + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + this[BUFFER] = Buffer.concat(buffers); -exports.analyze = function (domain, options = {}) { + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; - if (!domain) { // Catch null / undefined - return Errors.code('DOMAIN_NON_EMPTY_STRING'); - } + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); - if (typeof domain !== 'string') { - throw new Error('Invalid input: domain must be a string'); - } + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} - if (domain.length > 256) { - return Errors.code('DOMAIN_TOO_LONG'); - } +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); - const ascii = !internals.nonAsciiRx.test(domain); - if (!ascii) { - if (options.allowUnicode === false) { // Defaults to true - return Errors.code('DOMAIN_INVALID_UNICODE_CHARS'); - } +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); - domain = domain.normalize('NFC'); - } +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ - if (internals.domainControlRx.test(domain)) { - return Errors.code('DOMAIN_INVALID_CHARS'); - } +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); - domain = internals.punycode(domain); + this.message = message; + this.type = type; - // https://tools.ietf.org/html/rfc1035 section 2.3.1 + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } - if (options.allowFullyQualified && - domain[domain.length - 1] === '.') { + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} - domain = domain.slice(0, -1); - } +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; - const minDomainSegments = options.minDomainSegments || internals.minDomainSegments; +let convert; +try { + convert = (__nccwpck_require__(22877).convert); +} catch (e) {} - const segments = domain.split('.'); - if (segments.length < minDomainSegments) { - return Errors.code('DOMAIN_SEGMENTS_COUNT'); - } +const INTERNALS = Symbol('Body internals'); - if (options.maxDomainSegments) { - if (segments.length > options.maxDomainSegments) { - return Errors.code('DOMAIN_SEGMENTS_COUNT_MAX'); - } - } +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; - const tlds = options.tlds; - if (tlds) { - const tld = segments[segments.length - 1].toLowerCase(); - if (tlds.deny && tlds.deny.has(tld) || - tlds.allow && !tlds.allow.has(tld)) { +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; - return Errors.code('DOMAIN_FORBIDDEN_TLDS'); - } - } + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - if (!segment.length) { - return Errors.code('DOMAIN_EMPTY_SEGMENT'); - } + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; - if (segment.length > 63) { - return Errors.code('DOMAIN_LONG_SEGMENT'); - } + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} - if (i < segments.length - 1) { - if (!internals.domainSegmentRx.test(segment)) { - return Errors.code('DOMAIN_INVALID_CHARS'); - } - } - else { - if (!internals.tldSegmentRx.test(segment)) { - return Errors.code('DOMAIN_INVALID_TLDS_CHARS'); - } - } - } +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, - return null; -}; + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, -exports.isValid = function (domain, options) { + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, - return !exports.analyze(domain, options); -}; + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, -internals.punycode = function (domain) { + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, - if (domain.includes('%')) { - domain = domain.replace(/%/g, '%25'); - } + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, - try { - return new internals.URL(`http://${domain}`).host; - } - catch (err) { - return domain; - } + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } }; +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); -/***/ }), +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; -/***/ 3283: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; -"use strict"; + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + this[INTERNALS].disturbed = true; -const Util = __nccwpck_require__(73837); + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } -const Domain = __nccwpck_require__(97425); -const Errors = __nccwpck_require__(91594); + let body = this.body; + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } -const internals = { - nonAsciiRx: /[^\x00-\x7f]/, - encoder: new (Util.TextEncoder || TextEncoder)() // $lab:coverage:ignore$ -}; + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } -exports.analyze = function (email, options) { + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - return internals.email(email, options); -}; + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + return new Body.Promise(function (resolve, reject) { + let resTimeout; -exports.isValid = function (email, options) { + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } - return !internals.email(email, options); -}; + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } -internals.email = function (email, options = {}) { + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } - if (typeof email !== 'string') { - throw new Error('Invalid input: email must be a string'); - } + accumBytes += chunk.length; + accum.push(chunk); + }); - if (!email) { - return Errors.code('EMPTY_STRING'); - } + body.on('end', function () { + if (abort) { + return; + } - // Unicode + clearTimeout(resTimeout); - const ascii = !internals.nonAsciiRx.test(email); - if (!ascii) { - if (options.allowUnicode === false) { // Defaults to true - return Errors.code('FORBIDDEN_UNICODE'); - } + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} - email = email.normalize('NFC'); - } +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } - // Basic structure + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; - const parts = email.split('@'); - if (parts.length !== 2) { - return parts.length > 2 ? Errors.code('MULTIPLE_AT_CHAR') : Errors.code('MISSING_AT_CHAR'); - } + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } - const [local, domain] = parts; + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); - if (!local) { - return Errors.code('EMPTY_LOCAL'); - } + // html5 + if (!res && str) { + res = / 254) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3 - return Errors.code('ADDRESS_TOO_LONG'); - } + // html4 + if (!res && str) { + res = / 64) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 - return Errors.code('LOCAL_TOO_LONG'); - } - } + if (res) { + res = /charset=(.*)/i.exec(res.pop()); + } + } - // Validate parts + // xml + if (!res && str) { + res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str); + } - return internals.local(local, ascii) || Domain.analyze(domain, options); -}; + // found charset + if (res) { + charset = res.pop(); + // prevent decode issues when sites use incorrect encoding + // ref: https://hsivonen.fi/encoding-menu/ + if (charset === 'gb2312' || charset === 'gbk') { + charset = 'gb18030'; + } + } -internals.local = function (local, ascii) { + // turn raw buffers into a single utf-8 buffer + return convert(buffer, 'UTF-8', charset).toString(); +} - const segments = local.split('.'); - for (const segment of segments) { - if (!segment.length) { - return Errors.code('EMPTY_LOCAL_SEGMENT'); - } +/** + * Detect a URLSearchParams object + * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143 + * + * @param Object obj Object to detect by type or brand + * @return String + */ +function isURLSearchParams(obj) { + // Duck-typing as a necessary condition. + if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') { + return false; + } - if (ascii) { - if (!internals.atextRx.test(segment)) { - return Errors.code('INVALID_LOCAL_CHARS'); - } + // Brand-checking and more duck-typing as optional condition. + return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; +} - continue; - } +/** + * Check if `obj` is a W3C `Blob` object (which `File` inherits from) + * @param {*} obj + * @return {boolean} + */ +function isBlob(obj) { + return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]); +} - for (const char of segment) { - if (internals.atextRx.test(char)) { - continue; - } +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @return Mixed + */ +function clone(instance) { + let p1, p2; + let body = instance.body; - const binary = internals.binary(char); - if (!internals.atomRx.test(binary)) { - return Errors.code('INVALID_LOCAL_CHARS'); - } - } - } -}; + // don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } + // check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if (body instanceof Stream && typeof body.getBoundary !== 'function') { + // tee instance body + p1 = new PassThrough(); + p2 = new PassThrough(); + body.pipe(p1); + body.pipe(p2); + // set instance body to teed body and return the other teed body + instance[INTERNALS].body = p1; + body = p2; + } -internals.binary = function (char) { + return body; +} - return Array.from(internals.encoder.encode(char)).map((v) => String.fromCharCode(v)).join(''); -}; +/** + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param Mixed instance Any options.body input + */ +function extractContentType(body) { + if (body === null) { + // body is null + return null; + } else if (typeof body === 'string') { + // body is string + return 'text/plain;charset=UTF-8'; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isBlob(body)) { + // body is blob + return body.type || null; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return null; + } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + return null; + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + return null; + } else if (typeof body.getBoundary === 'function') { + // detect form data input from form-data module + return `multipart/form-data;boundary=${body.getBoundary()}`; + } else if (body instanceof Stream) { + // body is stream + // can't really do much about this + return null; + } else { + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; + } +} +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. + * + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * + * @param Body instance Instance of Body + * @return Number? Number of bytes, or null if not possible + */ +function getTotalBytes(instance) { + const body = instance.body; -/* - From RFC 5321: - Mailbox = Local-part "@" ( Domain / address-literal ) + if (body === null) { + // body is null + return 0; + } else if (isBlob(body)) { + return body.size; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + return null; + } +} - Local-part = Dot-string / Quoted-string - Dot-string = Atom *("." Atom) - Atom = 1*atext - atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void + */ +function writeToStream(dest, instance) { + const body = instance.body; - Domain = sub-domain *("." sub-domain) - sub-domain = Let-dig [Ldh-str] - Let-dig = ALPHA / DIGIT - Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig - ALPHA = %x41-5A / %x61-7A ; a-z, A-Z - DIGIT = %x30-39 ; 0-9 + if (body === null) { + // body is null + dest.end(); + } else if (isBlob(body)) { + body.stream().pipe(dest); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } +} - From RFC 6531: +// expose Promise +Body.Promise = global.Promise; - sub-domain =/ U-label - atext =/ UTF8-non-ascii +/** + * headers.js + * + * Headers class offers convenient helpers + */ - UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; - UTF8-2 = %xC2-DF UTF8-tail - UTF8-3 = %xE0 %xA0-BF UTF8-tail / - %xE1-EC 2( UTF8-tail ) / - %xED %x80-9F UTF8-tail / - %xEE-EF 2( UTF8-tail ) - UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / - %xF1-F3 3( UTF8-tail ) / - %xF4 %x80-8F 2( UTF8-tail ) +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } +} - UTF8-tail = %x80-BF +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } +} - Note: The following are not supported: +/** + * Find the key in the map object given a header name. + * + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined + */ +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; +} - RFC 5321: address-literal, Quoted-string - RFC 5322: obs-*, CFWS -*/ +const MAP = Symbol('map'); +class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + this[MAP] = Object.create(null); -internals.atextRx = /^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/; // _ included in \w + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } -internals.atomRx = new RegExp([ + return; + } - // %xC2-DF UTF8-tail - '(?:[\\xc2-\\xdf][\\x80-\\xbf])', + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } - // %xE0 %xA0-BF UTF8-tail %xE1-EC 2( UTF8-tail ) %xED %x80-9F UTF8-tail %xEE-EF 2( UTF8-tail ) - '(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})', + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } - // %xF0 %x90-BF 2( UTF8-tail ) %xF1-F3 3( UTF8-tail ) %xF4 %x80-8F 2( UTF8-tail ) - '(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})' + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } -].join('|')); + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + return this[MAP][key].join(', '); + } -/***/ }), + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; -/***/ 91594: -/***/ ((__unused_webpack_module, exports) => { + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; -"use strict"; + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } -exports.codes = { - EMPTY_STRING: 'Address must be a non-empty string', - FORBIDDEN_UNICODE: 'Address contains forbidden Unicode characters', - MULTIPLE_AT_CHAR: 'Address cannot contain more than one @ character', - MISSING_AT_CHAR: 'Address must contain one @ character', - EMPTY_LOCAL: 'Address local part cannot be empty', - ADDRESS_TOO_LONG: 'Address too long', - LOCAL_TOO_LONG: 'Address local part too long', - EMPTY_LOCAL_SEGMENT: 'Address local part contains empty dot-separated segment', - INVALID_LOCAL_CHARS: 'Address local part contains invalid character', - DOMAIN_NON_EMPTY_STRING: 'Domain must be a non-empty string', - DOMAIN_TOO_LONG: 'Domain too long', - DOMAIN_INVALID_UNICODE_CHARS: 'Domain contains forbidden Unicode characters', - DOMAIN_INVALID_CHARS: 'Domain contains invalid character', - DOMAIN_INVALID_TLDS_CHARS: 'Domain contains invalid tld character', - DOMAIN_SEGMENTS_COUNT: 'Domain lacks the minimum required number of segments', - DOMAIN_SEGMENTS_COUNT_MAX: 'Domain contains too many segments', - DOMAIN_FORBIDDEN_TLDS: 'Domain uses forbidden TLD', - DOMAIN_EMPTY_SEGMENT: 'Domain contains empty dot-separated segment', - DOMAIN_LONG_SEGMENT: 'Domain contains dot-separated segment that is too long' -}; + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } -exports.code = function (code) { + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } - return { code, error: exports.codes[code] }; -}; + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } -/***/ }), + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } -/***/ 82337: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; -"use strict"; +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); -const Assert = __nccwpck_require__(32718); +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; -const Uri = __nccwpck_require__(74983); + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} +const INTERNAL = Symbol('internal'); -const internals = {}; +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } -exports.regex = function (options = {}) { + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; - // CIDR + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } - Assert(options.cidr === undefined || typeof options.cidr === 'string', 'options.cidr must be a string'); - const cidr = options.cidr ? options.cidr.toLowerCase() : 'optional'; - Assert(['required', 'optional', 'forbidden'].includes(cidr), 'options.cidr must be one of required, optional, forbidden'); + this[INTERNAL].index = index + 1; - // Versions + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - Assert(options.version === undefined || typeof options.version === 'string' || Array.isArray(options.version), 'options.version must be a string or an array of string'); - let versions = options.version || ['ipv4', 'ipv6', 'ipvfuture']; - if (!Array.isArray(versions)) { - versions = [versions]; - } +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); - Assert(versions.length >= 1, 'options.version must have at least 1 version specified'); +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); - for (let i = 0; i < versions.length; ++i) { - Assert(typeof versions[i] === 'string', 'options.version must only contain strings'); - versions[i] = versions[i].toLowerCase(); - Assert(['ipv4', 'ipv6', 'ipvfuture'].includes(versions[i]), 'options.version contains unknown version ' + versions[i] + ' - must be one of ipv4, ipv6, ipvfuture'); - } + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } - versions = Array.from(new Set(versions)); + return obj; +} - // Regex +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} - const parts = versions.map((version) => { +const INTERNALS$1 = Symbol('Response internals'); - // Forbidden +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; - if (cidr === 'forbidden') { - return Uri.ip[version]; - } +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - // Required + Body.call(this, body, opts); - const cidrpart = `\\/${version === 'ipv4' ? Uri.ip.v4Cidr : Uri.ip.v6Cidr}`; + const status = opts.status || 200; + const headers = new Headers(opts.headers); - if (cidr === 'required') { - return `${Uri.ip[version]}${cidrpart}`; - } + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - // Optional + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } - return `${Uri.ip[version]}(?:${cidrpart})?`; - }); + get url() { + return this[INTERNALS$1].url || ''; + } - const raw = `(?:${parts.join('|')})`; - const regex = new RegExp(`^${raw}$`); - return { cidr, versions, regex, raw }; + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; -/***/ }), + return orig === dest; +}; -/***/ 53092: -/***/ ((module) => { +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { -"use strict"; + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + Body.Promise = fetch.Promise; -const internals = {}; + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; -// http://data.iana.org/TLD/tlds-alpha-by-domain.txt -// # Version 2022032102, Last Updated Tue Mar 22 07:07:01 2022 UTC + let response = null; + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; -internals.tlds = [ - 'AAA', - 'AARP', - 'ABARTH', - 'ABB', - 'ABBOTT', - 'ABBVIE', - 'ABC', - 'ABLE', - 'ABOGADO', - 'ABUDHABI', - 'AC', - 'ACADEMY', - 'ACCENTURE', - 'ACCOUNTANT', - 'ACCOUNTANTS', - 'ACO', - 'ACTOR', - 'AD', - 'ADAC', - 'ADS', - 'ADULT', - 'AE', - 'AEG', - 'AERO', - 'AETNA', - 'AF', - 'AFL', - 'AFRICA', - 'AG', - 'AGAKHAN', - 'AGENCY', - 'AI', - 'AIG', - 'AIRBUS', - 'AIRFORCE', - 'AIRTEL', - 'AKDN', - 'AL', - 'ALFAROMEO', - 'ALIBABA', - 'ALIPAY', - 'ALLFINANZ', - 'ALLSTATE', - 'ALLY', - 'ALSACE', - 'ALSTOM', - 'AM', - 'AMAZON', - 'AMERICANEXPRESS', - 'AMERICANFAMILY', - 'AMEX', - 'AMFAM', - 'AMICA', - 'AMSTERDAM', - 'ANALYTICS', - 'ANDROID', - 'ANQUAN', - 'ANZ', - 'AO', - 'AOL', - 'APARTMENTS', - 'APP', - 'APPLE', - 'AQ', - 'AQUARELLE', - 'AR', - 'ARAB', - 'ARAMCO', - 'ARCHI', - 'ARMY', - 'ARPA', - 'ART', - 'ARTE', - 'AS', - 'ASDA', - 'ASIA', - 'ASSOCIATES', - 'AT', - 'ATHLETA', - 'ATTORNEY', - 'AU', - 'AUCTION', - 'AUDI', - 'AUDIBLE', - 'AUDIO', - 'AUSPOST', - 'AUTHOR', - 'AUTO', - 'AUTOS', - 'AVIANCA', - 'AW', - 'AWS', - 'AX', - 'AXA', - 'AZ', - 'AZURE', - 'BA', - 'BABY', - 'BAIDU', - 'BANAMEX', - 'BANANAREPUBLIC', - 'BAND', - 'BANK', - 'BAR', - 'BARCELONA', - 'BARCLAYCARD', - 'BARCLAYS', - 'BAREFOOT', - 'BARGAINS', - 'BASEBALL', - 'BASKETBALL', - 'BAUHAUS', - 'BAYERN', - 'BB', - 'BBC', - 'BBT', - 'BBVA', - 'BCG', - 'BCN', - 'BD', - 'BE', - 'BEATS', - 'BEAUTY', - 'BEER', - 'BENTLEY', - 'BERLIN', - 'BEST', - 'BESTBUY', - 'BET', - 'BF', - 'BG', - 'BH', - 'BHARTI', - 'BI', - 'BIBLE', - 'BID', - 'BIKE', - 'BING', - 'BINGO', - 'BIO', - 'BIZ', - 'BJ', - 'BLACK', - 'BLACKFRIDAY', - 'BLOCKBUSTER', - 'BLOG', - 'BLOOMBERG', - 'BLUE', - 'BM', - 'BMS', - 'BMW', - 'BN', - 'BNPPARIBAS', - 'BO', - 'BOATS', - 'BOEHRINGER', - 'BOFA', - 'BOM', - 'BOND', - 'BOO', - 'BOOK', - 'BOOKING', - 'BOSCH', - 'BOSTIK', - 'BOSTON', - 'BOT', - 'BOUTIQUE', - 'BOX', - 'BR', - 'BRADESCO', - 'BRIDGESTONE', - 'BROADWAY', - 'BROKER', - 'BROTHER', - 'BRUSSELS', - 'BS', - 'BT', - 'BUGATTI', - 'BUILD', - 'BUILDERS', - 'BUSINESS', - 'BUY', - 'BUZZ', - 'BV', - 'BW', - 'BY', - 'BZ', - 'BZH', - 'CA', - 'CAB', - 'CAFE', - 'CAL', - 'CALL', - 'CALVINKLEIN', - 'CAM', - 'CAMERA', - 'CAMP', - 'CANCERRESEARCH', - 'CANON', - 'CAPETOWN', - 'CAPITAL', - 'CAPITALONE', - 'CAR', - 'CARAVAN', - 'CARDS', - 'CARE', - 'CAREER', - 'CAREERS', - 'CARS', - 'CASA', - 'CASE', - 'CASH', - 'CASINO', - 'CAT', - 'CATERING', - 'CATHOLIC', - 'CBA', - 'CBN', - 'CBRE', - 'CBS', - 'CC', - 'CD', - 'CENTER', - 'CEO', - 'CERN', - 'CF', - 'CFA', - 'CFD', - 'CG', - 'CH', - 'CHANEL', - 'CHANNEL', - 'CHARITY', - 'CHASE', - 'CHAT', - 'CHEAP', - 'CHINTAI', - 'CHRISTMAS', - 'CHROME', - 'CHURCH', - 'CI', - 'CIPRIANI', - 'CIRCLE', - 'CISCO', - 'CITADEL', - 'CITI', - 'CITIC', - 'CITY', - 'CITYEATS', - 'CK', - 'CL', - 'CLAIMS', - 'CLEANING', - 'CLICK', - 'CLINIC', - 'CLINIQUE', - 'CLOTHING', - 'CLOUD', - 'CLUB', - 'CLUBMED', - 'CM', - 'CN', - 'CO', - 'COACH', - 'CODES', - 'COFFEE', - 'COLLEGE', - 'COLOGNE', - 'COM', - 'COMCAST', - 'COMMBANK', - 'COMMUNITY', - 'COMPANY', - 'COMPARE', - 'COMPUTER', - 'COMSEC', - 'CONDOS', - 'CONSTRUCTION', - 'CONSULTING', - 'CONTACT', - 'CONTRACTORS', - 'COOKING', - 'COOKINGCHANNEL', - 'COOL', - 'COOP', - 'CORSICA', - 'COUNTRY', - 'COUPON', - 'COUPONS', - 'COURSES', - 'CPA', - 'CR', - 'CREDIT', - 'CREDITCARD', - 'CREDITUNION', - 'CRICKET', - 'CROWN', - 'CRS', - 'CRUISE', - 'CRUISES', - 'CU', - 'CUISINELLA', - 'CV', - 'CW', - 'CX', - 'CY', - 'CYMRU', - 'CYOU', - 'CZ', - 'DABUR', - 'DAD', - 'DANCE', - 'DATA', - 'DATE', - 'DATING', - 'DATSUN', - 'DAY', - 'DCLK', - 'DDS', - 'DE', - 'DEAL', - 'DEALER', - 'DEALS', - 'DEGREE', - 'DELIVERY', - 'DELL', - 'DELOITTE', - 'DELTA', - 'DEMOCRAT', - 'DENTAL', - 'DENTIST', - 'DESI', - 'DESIGN', - 'DEV', - 'DHL', - 'DIAMONDS', - 'DIET', - 'DIGITAL', - 'DIRECT', - 'DIRECTORY', - 'DISCOUNT', - 'DISCOVER', - 'DISH', - 'DIY', - 'DJ', - 'DK', - 'DM', - 'DNP', - 'DO', - 'DOCS', - 'DOCTOR', - 'DOG', - 'DOMAINS', - 'DOT', - 'DOWNLOAD', - 'DRIVE', - 'DTV', - 'DUBAI', - 'DUNLOP', - 'DUPONT', - 'DURBAN', - 'DVAG', - 'DVR', - 'DZ', - 'EARTH', - 'EAT', - 'EC', - 'ECO', - 'EDEKA', - 'EDU', - 'EDUCATION', - 'EE', - 'EG', - 'EMAIL', - 'EMERCK', - 'ENERGY', - 'ENGINEER', - 'ENGINEERING', - 'ENTERPRISES', - 'EPSON', - 'EQUIPMENT', - 'ER', - 'ERICSSON', - 'ERNI', - 'ES', - 'ESQ', - 'ESTATE', - 'ET', - 'ETISALAT', - 'EU', - 'EUROVISION', - 'EUS', - 'EVENTS', - 'EXCHANGE', - 'EXPERT', - 'EXPOSED', - 'EXPRESS', - 'EXTRASPACE', - 'FAGE', - 'FAIL', - 'FAIRWINDS', - 'FAITH', - 'FAMILY', - 'FAN', - 'FANS', - 'FARM', - 'FARMERS', - 'FASHION', - 'FAST', - 'FEDEX', - 'FEEDBACK', - 'FERRARI', - 'FERRERO', - 'FI', - 'FIAT', - 'FIDELITY', - 'FIDO', - 'FILM', - 'FINAL', - 'FINANCE', - 'FINANCIAL', - 'FIRE', - 'FIRESTONE', - 'FIRMDALE', - 'FISH', - 'FISHING', - 'FIT', - 'FITNESS', - 'FJ', - 'FK', - 'FLICKR', - 'FLIGHTS', - 'FLIR', - 'FLORIST', - 'FLOWERS', - 'FLY', - 'FM', - 'FO', - 'FOO', - 'FOOD', - 'FOODNETWORK', - 'FOOTBALL', - 'FORD', - 'FOREX', - 'FORSALE', - 'FORUM', - 'FOUNDATION', - 'FOX', - 'FR', - 'FREE', - 'FRESENIUS', - 'FRL', - 'FROGANS', - 'FRONTDOOR', - 'FRONTIER', - 'FTR', - 'FUJITSU', - 'FUN', - 'FUND', - 'FURNITURE', - 'FUTBOL', - 'FYI', - 'GA', - 'GAL', - 'GALLERY', - 'GALLO', - 'GALLUP', - 'GAME', - 'GAMES', - 'GAP', - 'GARDEN', - 'GAY', - 'GB', - 'GBIZ', - 'GD', - 'GDN', - 'GE', - 'GEA', - 'GENT', - 'GENTING', - 'GEORGE', - 'GF', - 'GG', - 'GGEE', - 'GH', - 'GI', - 'GIFT', - 'GIFTS', - 'GIVES', - 'GIVING', - 'GL', - 'GLASS', - 'GLE', - 'GLOBAL', - 'GLOBO', - 'GM', - 'GMAIL', - 'GMBH', - 'GMO', - 'GMX', - 'GN', - 'GODADDY', - 'GOLD', - 'GOLDPOINT', - 'GOLF', - 'GOO', - 'GOODYEAR', - 'GOOG', - 'GOOGLE', - 'GOP', - 'GOT', - 'GOV', - 'GP', - 'GQ', - 'GR', - 'GRAINGER', - 'GRAPHICS', - 'GRATIS', - 'GREEN', - 'GRIPE', - 'GROCERY', - 'GROUP', - 'GS', - 'GT', - 'GU', - 'GUARDIAN', - 'GUCCI', - 'GUGE', - 'GUIDE', - 'GUITARS', - 'GURU', - 'GW', - 'GY', - 'HAIR', - 'HAMBURG', - 'HANGOUT', - 'HAUS', - 'HBO', - 'HDFC', - 'HDFCBANK', - 'HEALTH', - 'HEALTHCARE', - 'HELP', - 'HELSINKI', - 'HERE', - 'HERMES', - 'HGTV', - 'HIPHOP', - 'HISAMITSU', - 'HITACHI', - 'HIV', - 'HK', - 'HKT', - 'HM', - 'HN', - 'HOCKEY', - 'HOLDINGS', - 'HOLIDAY', - 'HOMEDEPOT', - 'HOMEGOODS', - 'HOMES', - 'HOMESENSE', - 'HONDA', - 'HORSE', - 'HOSPITAL', - 'HOST', - 'HOSTING', - 'HOT', - 'HOTELES', - 'HOTELS', - 'HOTMAIL', - 'HOUSE', - 'HOW', - 'HR', - 'HSBC', - 'HT', - 'HU', - 'HUGHES', - 'HYATT', - 'HYUNDAI', - 'IBM', - 'ICBC', - 'ICE', - 'ICU', - 'ID', - 'IE', - 'IEEE', - 'IFM', - 'IKANO', - 'IL', - 'IM', - 'IMAMAT', - 'IMDB', - 'IMMO', - 'IMMOBILIEN', - 'IN', - 'INC', - 'INDUSTRIES', - 'INFINITI', - 'INFO', - 'ING', - 'INK', - 'INSTITUTE', - 'INSURANCE', - 'INSURE', - 'INT', - 'INTERNATIONAL', - 'INTUIT', - 'INVESTMENTS', - 'IO', - 'IPIRANGA', - 'IQ', - 'IR', - 'IRISH', - 'IS', - 'ISMAILI', - 'IST', - 'ISTANBUL', - 'IT', - 'ITAU', - 'ITV', - 'JAGUAR', - 'JAVA', - 'JCB', - 'JE', - 'JEEP', - 'JETZT', - 'JEWELRY', - 'JIO', - 'JLL', - 'JM', - 'JMP', - 'JNJ', - 'JO', - 'JOBS', - 'JOBURG', - 'JOT', - 'JOY', - 'JP', - 'JPMORGAN', - 'JPRS', - 'JUEGOS', - 'JUNIPER', - 'KAUFEN', - 'KDDI', - 'KE', - 'KERRYHOTELS', - 'KERRYLOGISTICS', - 'KERRYPROPERTIES', - 'KFH', - 'KG', - 'KH', - 'KI', - 'KIA', - 'KIM', - 'KINDER', - 'KINDLE', - 'KITCHEN', - 'KIWI', - 'KM', - 'KN', - 'KOELN', - 'KOMATSU', - 'KOSHER', - 'KP', - 'KPMG', - 'KPN', - 'KR', - 'KRD', - 'KRED', - 'KUOKGROUP', - 'KW', - 'KY', - 'KYOTO', - 'KZ', - 'LA', - 'LACAIXA', - 'LAMBORGHINI', - 'LAMER', - 'LANCASTER', - 'LANCIA', - 'LAND', - 'LANDROVER', - 'LANXESS', - 'LASALLE', - 'LAT', - 'LATINO', - 'LATROBE', - 'LAW', - 'LAWYER', - 'LB', - 'LC', - 'LDS', - 'LEASE', - 'LECLERC', - 'LEFRAK', - 'LEGAL', - 'LEGO', - 'LEXUS', - 'LGBT', - 'LI', - 'LIDL', - 'LIFE', - 'LIFEINSURANCE', - 'LIFESTYLE', - 'LIGHTING', - 'LIKE', - 'LILLY', - 'LIMITED', - 'LIMO', - 'LINCOLN', - 'LINDE', - 'LINK', - 'LIPSY', - 'LIVE', - 'LIVING', - 'LK', - 'LLC', - 'LLP', - 'LOAN', - 'LOANS', - 'LOCKER', - 'LOCUS', - 'LOFT', - 'LOL', - 'LONDON', - 'LOTTE', - 'LOTTO', - 'LOVE', - 'LPL', - 'LPLFINANCIAL', - 'LR', - 'LS', - 'LT', - 'LTD', - 'LTDA', - 'LU', - 'LUNDBECK', - 'LUXE', - 'LUXURY', - 'LV', - 'LY', - 'MA', - 'MACYS', - 'MADRID', - 'MAIF', - 'MAISON', - 'MAKEUP', - 'MAN', - 'MANAGEMENT', - 'MANGO', - 'MAP', - 'MARKET', - 'MARKETING', - 'MARKETS', - 'MARRIOTT', - 'MARSHALLS', - 'MASERATI', - 'MATTEL', - 'MBA', - 'MC', - 'MCKINSEY', - 'MD', - 'ME', - 'MED', - 'MEDIA', - 'MEET', - 'MELBOURNE', - 'MEME', - 'MEMORIAL', - 'MEN', - 'MENU', - 'MERCKMSD', - 'MG', - 'MH', - 'MIAMI', - 'MICROSOFT', - 'MIL', - 'MINI', - 'MINT', - 'MIT', - 'MITSUBISHI', - 'MK', - 'ML', - 'MLB', - 'MLS', - 'MM', - 'MMA', - 'MN', - 'MO', - 'MOBI', - 'MOBILE', - 'MODA', - 'MOE', - 'MOI', - 'MOM', - 'MONASH', - 'MONEY', - 'MONSTER', - 'MORMON', - 'MORTGAGE', - 'MOSCOW', - 'MOTO', - 'MOTORCYCLES', - 'MOV', - 'MOVIE', - 'MP', - 'MQ', - 'MR', - 'MS', - 'MSD', - 'MT', - 'MTN', - 'MTR', - 'MU', - 'MUSEUM', - 'MUSIC', - 'MUTUAL', - 'MV', - 'MW', - 'MX', - 'MY', - 'MZ', - 'NA', - 'NAB', - 'NAGOYA', - 'NAME', - 'NATURA', - 'NAVY', - 'NBA', - 'NC', - 'NE', - 'NEC', - 'NET', - 'NETBANK', - 'NETFLIX', - 'NETWORK', - 'NEUSTAR', - 'NEW', - 'NEWS', - 'NEXT', - 'NEXTDIRECT', - 'NEXUS', - 'NF', - 'NFL', - 'NG', - 'NGO', - 'NHK', - 'NI', - 'NICO', - 'NIKE', - 'NIKON', - 'NINJA', - 'NISSAN', - 'NISSAY', - 'NL', - 'NO', - 'NOKIA', - 'NORTHWESTERNMUTUAL', - 'NORTON', - 'NOW', - 'NOWRUZ', - 'NOWTV', - 'NP', - 'NR', - 'NRA', - 'NRW', - 'NTT', - 'NU', - 'NYC', - 'NZ', - 'OBI', - 'OBSERVER', - 'OFFICE', - 'OKINAWA', - 'OLAYAN', - 'OLAYANGROUP', - 'OLDNAVY', - 'OLLO', - 'OM', - 'OMEGA', - 'ONE', - 'ONG', - 'ONL', - 'ONLINE', - 'OOO', - 'OPEN', - 'ORACLE', - 'ORANGE', - 'ORG', - 'ORGANIC', - 'ORIGINS', - 'OSAKA', - 'OTSUKA', - 'OTT', - 'OVH', - 'PA', - 'PAGE', - 'PANASONIC', - 'PARIS', - 'PARS', - 'PARTNERS', - 'PARTS', - 'PARTY', - 'PASSAGENS', - 'PAY', - 'PCCW', - 'PE', - 'PET', - 'PF', - 'PFIZER', - 'PG', - 'PH', - 'PHARMACY', - 'PHD', - 'PHILIPS', - 'PHONE', - 'PHOTO', - 'PHOTOGRAPHY', - 'PHOTOS', - 'PHYSIO', - 'PICS', - 'PICTET', - 'PICTURES', - 'PID', - 'PIN', - 'PING', - 'PINK', - 'PIONEER', - 'PIZZA', - 'PK', - 'PL', - 'PLACE', - 'PLAY', - 'PLAYSTATION', - 'PLUMBING', - 'PLUS', - 'PM', - 'PN', - 'PNC', - 'POHL', - 'POKER', - 'POLITIE', - 'PORN', - 'POST', - 'PR', - 'PRAMERICA', - 'PRAXI', - 'PRESS', - 'PRIME', - 'PRO', - 'PROD', - 'PRODUCTIONS', - 'PROF', - 'PROGRESSIVE', - 'PROMO', - 'PROPERTIES', - 'PROPERTY', - 'PROTECTION', - 'PRU', - 'PRUDENTIAL', - 'PS', - 'PT', - 'PUB', - 'PW', - 'PWC', - 'PY', - 'QA', - 'QPON', - 'QUEBEC', - 'QUEST', - 'RACING', - 'RADIO', - 'RE', - 'READ', - 'REALESTATE', - 'REALTOR', - 'REALTY', - 'RECIPES', - 'RED', - 'REDSTONE', - 'REDUMBRELLA', - 'REHAB', - 'REISE', - 'REISEN', - 'REIT', - 'RELIANCE', - 'REN', - 'RENT', - 'RENTALS', - 'REPAIR', - 'REPORT', - 'REPUBLICAN', - 'REST', - 'RESTAURANT', - 'REVIEW', - 'REVIEWS', - 'REXROTH', - 'RICH', - 'RICHARDLI', - 'RICOH', - 'RIL', - 'RIO', - 'RIP', - 'RO', - 'ROCHER', - 'ROCKS', - 'RODEO', - 'ROGERS', - 'ROOM', - 'RS', - 'RSVP', - 'RU', - 'RUGBY', - 'RUHR', - 'RUN', - 'RW', - 'RWE', - 'RYUKYU', - 'SA', - 'SAARLAND', - 'SAFE', - 'SAFETY', - 'SAKURA', - 'SALE', - 'SALON', - 'SAMSCLUB', - 'SAMSUNG', - 'SANDVIK', - 'SANDVIKCOROMANT', - 'SANOFI', - 'SAP', - 'SARL', - 'SAS', - 'SAVE', - 'SAXO', - 'SB', - 'SBI', - 'SBS', - 'SC', - 'SCA', - 'SCB', - 'SCHAEFFLER', - 'SCHMIDT', - 'SCHOLARSHIPS', - 'SCHOOL', - 'SCHULE', - 'SCHWARZ', - 'SCIENCE', - 'SCOT', - 'SD', - 'SE', - 'SEARCH', - 'SEAT', - 'SECURE', - 'SECURITY', - 'SEEK', - 'SELECT', - 'SENER', - 'SERVICES', - 'SES', - 'SEVEN', - 'SEW', - 'SEX', - 'SEXY', - 'SFR', - 'SG', - 'SH', - 'SHANGRILA', - 'SHARP', - 'SHAW', - 'SHELL', - 'SHIA', - 'SHIKSHA', - 'SHOES', - 'SHOP', - 'SHOPPING', - 'SHOUJI', - 'SHOW', - 'SHOWTIME', - 'SI', - 'SILK', - 'SINA', - 'SINGLES', - 'SITE', - 'SJ', - 'SK', - 'SKI', - 'SKIN', - 'SKY', - 'SKYPE', - 'SL', - 'SLING', - 'SM', - 'SMART', - 'SMILE', - 'SN', - 'SNCF', - 'SO', - 'SOCCER', - 'SOCIAL', - 'SOFTBANK', - 'SOFTWARE', - 'SOHU', - 'SOLAR', - 'SOLUTIONS', - 'SONG', - 'SONY', - 'SOY', - 'SPA', - 'SPACE', - 'SPORT', - 'SPOT', - 'SR', - 'SRL', - 'SS', - 'ST', - 'STADA', - 'STAPLES', - 'STAR', - 'STATEBANK', - 'STATEFARM', - 'STC', - 'STCGROUP', - 'STOCKHOLM', - 'STORAGE', - 'STORE', - 'STREAM', - 'STUDIO', - 'STUDY', - 'STYLE', - 'SU', - 'SUCKS', - 'SUPPLIES', - 'SUPPLY', - 'SUPPORT', - 'SURF', - 'SURGERY', - 'SUZUKI', - 'SV', - 'SWATCH', - 'SWISS', - 'SX', - 'SY', - 'SYDNEY', - 'SYSTEMS', - 'SZ', - 'TAB', - 'TAIPEI', - 'TALK', - 'TAOBAO', - 'TARGET', - 'TATAMOTORS', - 'TATAR', - 'TATTOO', - 'TAX', - 'TAXI', - 'TC', - 'TCI', - 'TD', - 'TDK', - 'TEAM', - 'TECH', - 'TECHNOLOGY', - 'TEL', - 'TEMASEK', - 'TENNIS', - 'TEVA', - 'TF', - 'TG', - 'TH', - 'THD', - 'THEATER', - 'THEATRE', - 'TIAA', - 'TICKETS', - 'TIENDA', - 'TIFFANY', - 'TIPS', - 'TIRES', - 'TIROL', - 'TJ', - 'TJMAXX', - 'TJX', - 'TK', - 'TKMAXX', - 'TL', - 'TM', - 'TMALL', - 'TN', - 'TO', - 'TODAY', - 'TOKYO', - 'TOOLS', - 'TOP', - 'TORAY', - 'TOSHIBA', - 'TOTAL', - 'TOURS', - 'TOWN', - 'TOYOTA', - 'TOYS', - 'TR', - 'TRADE', - 'TRADING', - 'TRAINING', - 'TRAVEL', - 'TRAVELCHANNEL', - 'TRAVELERS', - 'TRAVELERSINSURANCE', - 'TRUST', - 'TRV', - 'TT', - 'TUBE', - 'TUI', - 'TUNES', - 'TUSHU', - 'TV', - 'TVS', - 'TW', - 'TZ', - 'UA', - 'UBANK', - 'UBS', - 'UG', - 'UK', - 'UNICOM', - 'UNIVERSITY', - 'UNO', - 'UOL', - 'UPS', - 'US', - 'UY', - 'UZ', - 'VA', - 'VACATIONS', - 'VANA', - 'VANGUARD', - 'VC', - 'VE', - 'VEGAS', - 'VENTURES', - 'VERISIGN', - 'VERSICHERUNG', - 'VET', - 'VG', - 'VI', - 'VIAJES', - 'VIDEO', - 'VIG', - 'VIKING', - 'VILLAS', - 'VIN', - 'VIP', - 'VIRGIN', - 'VISA', - 'VISION', - 'VIVA', - 'VIVO', - 'VLAANDEREN', - 'VN', - 'VODKA', - 'VOLKSWAGEN', - 'VOLVO', - 'VOTE', - 'VOTING', - 'VOTO', - 'VOYAGE', - 'VU', - 'VUELOS', - 'WALES', - 'WALMART', - 'WALTER', - 'WANG', - 'WANGGOU', - 'WATCH', - 'WATCHES', - 'WEATHER', - 'WEATHERCHANNEL', - 'WEBCAM', - 'WEBER', - 'WEBSITE', - 'WED', - 'WEDDING', - 'WEIBO', - 'WEIR', - 'WF', - 'WHOSWHO', - 'WIEN', - 'WIKI', - 'WILLIAMHILL', - 'WIN', - 'WINDOWS', - 'WINE', - 'WINNERS', - 'WME', - 'WOLTERSKLUWER', - 'WOODSIDE', - 'WORK', - 'WORKS', - 'WORLD', - 'WOW', - 'WS', - 'WTC', - 'WTF', - 'XBOX', - 'XEROX', - 'XFINITY', - 'XIHUAN', - 'XIN', - 'XN--11B4C3D', - 'XN--1CK2E1B', - 'XN--1QQW23A', - 'XN--2SCRJ9C', - 'XN--30RR7Y', - 'XN--3BST00M', - 'XN--3DS443G', - 'XN--3E0B707E', - 'XN--3HCRJ9C', - 'XN--3PXU8K', - 'XN--42C2D9A', - 'XN--45BR5CYL', - 'XN--45BRJ9C', - 'XN--45Q11C', - 'XN--4DBRK0CE', - 'XN--4GBRIM', - 'XN--54B7FTA0CC', - 'XN--55QW42G', - 'XN--55QX5D', - 'XN--5SU34J936BGSG', - 'XN--5TZM5G', - 'XN--6FRZ82G', - 'XN--6QQ986B3XL', - 'XN--80ADXHKS', - 'XN--80AO21A', - 'XN--80AQECDR1A', - 'XN--80ASEHDB', - 'XN--80ASWG', - 'XN--8Y0A063A', - 'XN--90A3AC', - 'XN--90AE', - 'XN--90AIS', - 'XN--9DBQ2A', - 'XN--9ET52U', - 'XN--9KRT00A', - 'XN--B4W605FERD', - 'XN--BCK1B9A5DRE4C', - 'XN--C1AVG', - 'XN--C2BR7G', - 'XN--CCK2B3B', - 'XN--CCKWCXETD', - 'XN--CG4BKI', - 'XN--CLCHC0EA0B2G2A9GCD', - 'XN--CZR694B', - 'XN--CZRS0T', - 'XN--CZRU2D', - 'XN--D1ACJ3B', - 'XN--D1ALF', - 'XN--E1A4C', - 'XN--ECKVDTC9D', - 'XN--EFVY88H', - 'XN--FCT429K', - 'XN--FHBEI', - 'XN--FIQ228C5HS', - 'XN--FIQ64B', - 'XN--FIQS8S', - 'XN--FIQZ9S', - 'XN--FJQ720A', - 'XN--FLW351E', - 'XN--FPCRJ9C3D', - 'XN--FZC2C9E2C', - 'XN--FZYS8D69UVGM', - 'XN--G2XX48C', - 'XN--GCKR3F0F', - 'XN--GECRJ9C', - 'XN--GK3AT1E', - 'XN--H2BREG3EVE', - 'XN--H2BRJ9C', - 'XN--H2BRJ9C8C', - 'XN--HXT814E', - 'XN--I1B6B1A6A2E', - 'XN--IMR513N', - 'XN--IO0A7I', - 'XN--J1AEF', - 'XN--J1AMH', - 'XN--J6W193G', - 'XN--JLQ480N2RG', - 'XN--JLQ61U9W7B', - 'XN--JVR189M', - 'XN--KCRX77D1X4A', - 'XN--KPRW13D', - 'XN--KPRY57D', - 'XN--KPUT3I', - 'XN--L1ACC', - 'XN--LGBBAT1AD8J', - 'XN--MGB9AWBF', - 'XN--MGBA3A3EJT', - 'XN--MGBA3A4F16A', - 'XN--MGBA7C0BBN0A', - 'XN--MGBAAKC7DVF', - 'XN--MGBAAM7A8H', - 'XN--MGBAB2BD', - 'XN--MGBAH1A3HJKRD', - 'XN--MGBAI9AZGQP6J', - 'XN--MGBAYH7GPA', - 'XN--MGBBH1A', - 'XN--MGBBH1A71E', - 'XN--MGBC0A9AZCG', - 'XN--MGBCA7DZDO', - 'XN--MGBCPQ6GPA1A', - 'XN--MGBERP4A5D4AR', - 'XN--MGBGU82A', - 'XN--MGBI4ECEXP', - 'XN--MGBPL2FH', - 'XN--MGBT3DHD', - 'XN--MGBTX2B', - 'XN--MGBX4CD0AB', - 'XN--MIX891F', - 'XN--MK1BU44C', - 'XN--MXTQ1M', - 'XN--NGBC5AZD', - 'XN--NGBE9E0A', - 'XN--NGBRX', - 'XN--NODE', - 'XN--NQV7F', - 'XN--NQV7FS00EMA', - 'XN--NYQY26A', - 'XN--O3CW4H', - 'XN--OGBPF8FL', - 'XN--OTU796D', - 'XN--P1ACF', - 'XN--P1AI', - 'XN--PGBS0DH', - 'XN--PSSY2U', - 'XN--Q7CE6A', - 'XN--Q9JYB4C', - 'XN--QCKA1PMC', - 'XN--QXA6A', - 'XN--QXAM', - 'XN--RHQV96G', - 'XN--ROVU88B', - 'XN--RVC1E0AM3E', - 'XN--S9BRJ9C', - 'XN--SES554G', - 'XN--T60B56A', - 'XN--TCKWE', - 'XN--TIQ49XQYJ', - 'XN--UNUP4Y', - 'XN--VERMGENSBERATER-CTB', - 'XN--VERMGENSBERATUNG-PWB', - 'XN--VHQUV', - 'XN--VUQ861B', - 'XN--W4R85EL8FHU5DNRA', - 'XN--W4RS40L', - 'XN--WGBH1C', - 'XN--WGBL6A', - 'XN--XHQ521B', - 'XN--XKC2AL3HYE2A', - 'XN--XKC2DL3A5EE0H', - 'XN--Y9A3AQ', - 'XN--YFRO4I67O', - 'XN--YGBI2AMMX', - 'XN--ZFR164B', - 'XXX', - 'XYZ', - 'YACHTS', - 'YAHOO', - 'YAMAXUN', - 'YANDEX', - 'YE', - 'YODOBASHI', - 'YOGA', - 'YOKOHAMA', - 'YOU', - 'YOUTUBE', - 'YT', - 'YUN', - 'ZA', - 'ZAPPOS', - 'ZARA', - 'ZERO', - 'ZIP', - 'ZM', - 'ZONE', - 'ZUERICH', - 'ZW' -]; - - -// Keep as upper-case to make updating from source easier - -module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase())); - - -/***/ }), - -/***/ 74983: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const EscapeRegex = __nccwpck_require__(91965); - - -const internals = {}; - - -internals.generate = function () { - - const rfc3986 = {}; - - const hexDigit = '\\dA-Fa-f'; // HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" - const hexDigitOnly = '[' + hexDigit + ']'; - - const unreserved = '\\w-\\.~'; // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - const subDelims = '!\\$&\'\\(\\)\\*\\+,;='; // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - const pctEncoded = '%' + hexDigit; // pct-encoded = "%" HEXDIG HEXDIG - const pchar = unreserved + pctEncoded + subDelims + ':@'; // pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - const pcharOnly = '[' + pchar + ']'; - const decOctect = '(?:0{0,2}\\d|0?[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])'; // dec-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35 ; 0-9 / 10-99 / 100-199 / 200-249 / 250-255 - - rfc3986.ipv4address = '(?:' + decOctect + '\\.){3}' + decOctect; // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - - /* - h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal - ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address - IPv6address = 6( h16 ":" ) ls32 - / "::" 5( h16 ":" ) ls32 - / [ h16 ] "::" 4( h16 ":" ) ls32 - / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - / [ *4( h16 ":" ) h16 ] "::" ls32 - / [ *5( h16 ":" ) h16 ] "::" h16 - / [ *6( h16 ":" ) h16 ] "::" - */ - - const h16 = hexDigitOnly + '{1,4}'; - const ls32 = '(?:' + h16 + ':' + h16 + '|' + rfc3986.ipv4address + ')'; - const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32; - const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32; - const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32; - const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32; - const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32; - const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32; - const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32; - const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16; - const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::'; - - rfc3986.ipv4Cidr = '(?:\\d|[1-2]\\d|3[0-2])'; // IPv4 cidr = DIGIT / %x31-32 DIGIT / "3" %x30-32 ; 0-9 / 10-29 / 30-32 - rfc3986.ipv6Cidr = '(?:0{0,2}\\d|0?[1-9]\\d|1[01]\\d|12[0-8])'; // IPv6 cidr = DIGIT / %x31-39 DIGIT / "1" %x0-1 DIGIT / "12" %x0-8; 0-9 / 10-99 / 100-119 / 120-128 - rfc3986.ipv6address = '(?:' + IPv6SixHex + '|' + IPv6FiveHex + '|' + IPv6FourHex + '|' + IPv6ThreeHex + '|' + IPv6TwoHex + '|' + IPv6OneHex + '|' + IPv6NoneHex + '|' + IPv6NoneHex2 + '|' + IPv6NoneHex3 + ')'; - rfc3986.ipvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; // IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) - - rfc3986.scheme = '[a-zA-Z][a-zA-Z\\d+-\\.]*'; // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - rfc3986.schemeRegex = new RegExp(rfc3986.scheme); - - const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; // userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) - const IPLiteral = '\\[(?:' + rfc3986.ipv6address + '|' + rfc3986.ipvFuture + ')\\]'; // IP-literal = "[" ( IPv6address / IPvFuture ) "]" - const regName = '[' + unreserved + pctEncoded + subDelims + ']{1,255}'; // reg-name = *( unreserved / pct-encoded / sub-delims ) - const host = '(?:' + IPLiteral + '|' + rfc3986.ipv4address + '|' + regName + ')'; // host = IP-literal / IPv4address / reg-name - const port = '\\d*'; // port = *DIGIT - const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; // authority = [ userinfo "@" ] host [ ":" port ] - const authorityCapture = '(?:' + userinfo + '@)?(' + host + ')(?::' + port + ')?'; - - /* - segment = *pchar - segment-nz = 1*pchar - path = path-abempty ; begins with "/" '|' is empty - / path-absolute ; begins with "/" but not "//" - / path-noscheme ; begins with a non-colon segment - / path-rootless ; begins with a segment - / path-empty ; zero characters - path-abempty = *( "/" segment ) - path-absolute = "/" [ segment-nz *( "/" segment ) ] - path-rootless = segment-nz *( "/" segment ) - */ - - const segment = pcharOnly + '*'; - const segmentNz = pcharOnly + '+'; - const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+'; - const pathEmpty = ''; - const pathAbEmpty = '(?:\\/' + segment + ')*'; - const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?'; - const pathRootless = segmentNz + pathAbEmpty; - const pathNoScheme = segmentNzNc + pathAbEmpty; - const pathAbNoAuthority = '(?:\\/\\/\\/' + segment + pathAbEmpty + ')'; // Used by file:/// - - // hier-part = "//" authority path - - rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + '|' + pathAbNoAuthority + ')'; - rfc3986.hierPartCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + ')'; - - // relative-part = "//" authority path-abempty / path-absolute / path-noscheme / path-empty - - rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; - rfc3986.relativeRefCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; - - // query = *( pchar / "/" / "?" ) - // query = *( pchar / "[" / "]" / "/" / "?" ) - - rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part '|' end of the line. - rfc3986.queryWithSquareBrackets = '[' + pchar + '\\[\\]\\/\\?]*(?=#|$)'; - - // fragment = *( pchar / "/" / "?" ) - - rfc3986.fragment = '[' + pchar + '\\/\\?]*'; - - return rfc3986; -}; - -internals.rfc3986 = internals.generate(); - - -exports.ip = { - v4Cidr: internals.rfc3986.ipv4Cidr, - v6Cidr: internals.rfc3986.ipv6Cidr, - ipv4: internals.rfc3986.ipv4address, - ipv6: internals.rfc3986.ipv6address, - ipvfuture: internals.rfc3986.ipvFuture -}; - - -internals.createRegex = function (options) { - - const rfc = internals.rfc3986; - - // Construct expression - - const query = options.allowQuerySquareBrackets ? rfc.queryWithSquareBrackets : rfc.query; - const suffix = '(?:\\?' + query + ')?' + '(?:#' + rfc.fragment + ')?'; - - // relative-ref = relative-part [ "?" query ] [ "#" fragment ] - - const relative = options.domain ? rfc.relativeRefCapture : rfc.relativeRef; - - if (options.relativeOnly) { - return internals.wrap(relative + suffix); - } - - // Custom schemes - - let customScheme = ''; - if (options.scheme) { - Assert(options.scheme instanceof RegExp || typeof options.scheme === 'string' || Array.isArray(options.scheme), 'scheme must be a RegExp, String, or Array'); - - const schemes = [].concat(options.scheme); - Assert(schemes.length >= 1, 'scheme must have at least 1 scheme specified'); - - // Flatten the array into a string to be used to match the schemes - - const selections = []; - for (let i = 0; i < schemes.length; ++i) { - const scheme = schemes[i]; - Assert(scheme instanceof RegExp || typeof scheme === 'string', 'scheme at position ' + i + ' must be a RegExp or String'); - - if (scheme instanceof RegExp) { - selections.push(scheme.source.toString()); - } - else { - Assert(rfc.schemeRegex.test(scheme), 'scheme at position ' + i + ' must be a valid scheme'); - selections.push(EscapeRegex(scheme)); - } - } - - customScheme = selections.join('|'); - } - - // URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] - - const scheme = customScheme ? '(?:' + customScheme + ')' : rfc.scheme; - const absolute = '(?:' + scheme + ':' + (options.domain ? rfc.hierPartCapture : rfc.hierPart) + ')'; - const prefix = options.allowRelative ? '(?:' + absolute + '|' + relative + ')' : absolute; - return internals.wrap(prefix + suffix, customScheme); -}; - - -internals.wrap = function (raw, scheme) { - - raw = `(?=.)(?!https?\:/(?:$|[^/]))(?!https?\:///)(?!https?\:[^/])${raw}`; // Require at least one character and explicitly forbid 'http:/' or HTTP with empty domain - - return { - raw, - regex: new RegExp(`^${raw}$`), - scheme - }; -}; - - -internals.uriRegex = internals.createRegex({}); - - -exports.regex = function (options = {}) { - - if (options.scheme || - options.allowRelative || - options.relativeOnly || - options.allowQuerySquareBrackets || - options.domain) { - - return internals.createRegex(options); - } - - return internals.uriRegex; -}; - - -/***/ }), - -/***/ 34379: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const internals = { - operators: ['!', '^', '*', '/', '%', '+', '-', '<', '<=', '>', '>=', '==', '!=', '&&', '||', '??'], - operatorCharacters: ['!', '^', '*', '/', '%', '+', '-', '<', '=', '>', '&', '|', '?'], - operatorsOrder: [['^'], ['*', '/', '%'], ['+', '-'], ['<', '<=', '>', '>='], ['==', '!='], ['&&'], ['||', '??']], - operatorsPrefix: ['!', 'n'], - - literals: { - '"': '"', - '`': '`', - '\'': '\'', - '[': ']' - }, - - numberRx: /^(?:[0-9]*(\.[0-9]*)?){1}$/, - tokenRx: /^[\w\$\#\.\@\:\{\}]+$/, - - symbol: Symbol('formula'), - settings: Symbol('settings') -}; - - -exports.Parser = class { - - constructor(string, options = {}) { - - if (!options[internals.settings] && - options.constants) { - - for (const constant in options.constants) { - const value = options.constants[constant]; - if (value !== null && - !['boolean', 'number', 'string'].includes(typeof value)) { - - throw new Error(`Formula constant ${constant} contains invalid ${typeof value} value type`); - } - } - } - - this.settings = options[internals.settings] ? options : Object.assign({ [internals.settings]: true, constants: {}, functions: {} }, options); - this.single = null; - - this._parts = null; - this._parse(string); - } - - _parse(string) { - - let parts = []; - let current = ''; - let parenthesis = 0; - let literal = false; - - const flush = (inner) => { - - if (parenthesis) { - throw new Error('Formula missing closing parenthesis'); - } - - const last = parts.length ? parts[parts.length - 1] : null; - - if (!literal && - !current && - !inner) { - - return; - } - - if (last && - last.type === 'reference' && - inner === ')') { // Function - - last.type = 'function'; - last.value = this._subFormula(current, last.value); - current = ''; - return; - } - - if (inner === ')') { // Segment - const sub = new exports.Parser(current, this.settings); - parts.push({ type: 'segment', value: sub }); - } - else if (literal) { - if (literal === ']') { // Reference - parts.push({ type: 'reference', value: current }); - current = ''; - return; - } - - parts.push({ type: 'literal', value: current }); // Literal - } - else if (internals.operatorCharacters.includes(current)) { // Operator - if (last && - last.type === 'operator' && - internals.operators.includes(last.value + current)) { // 2 characters operator - - last.value += current; - } - else { - parts.push({ type: 'operator', value: current }); - } - } - else if (current.match(internals.numberRx)) { // Number - parts.push({ type: 'constant', value: parseFloat(current) }); - } - else if (this.settings.constants[current] !== undefined) { // Constant - parts.push({ type: 'constant', value: this.settings.constants[current] }); - } - else { // Reference - if (!current.match(internals.tokenRx)) { - throw new Error(`Formula contains invalid token: ${current}`); - } - - parts.push({ type: 'reference', value: current }); - } - - current = ''; - }; - - for (const c of string) { - if (literal) { - if (c === literal) { - flush(); - literal = false; - } - else { - current += c; - } - } - else if (parenthesis) { - if (c === '(') { - current += c; - ++parenthesis; - } - else if (c === ')') { - --parenthesis; - if (!parenthesis) { - flush(c); - } - else { - current += c; - } - } - else { - current += c; - } - } - else if (c in internals.literals) { - literal = internals.literals[c]; - } - else if (c === '(') { - flush(); - ++parenthesis; - } - else if (internals.operatorCharacters.includes(c)) { - flush(); - current = c; - flush(); - } - else if (c !== ' ') { - current += c; - } - else { - flush(); - } - } - - flush(); - - // Replace prefix - to internal negative operator - - parts = parts.map((part, i) => { - - if (part.type !== 'operator' || - part.value !== '-' || - i && parts[i - 1].type !== 'operator') { - - return part; - } - - return { type: 'operator', value: 'n' }; - }); - - // Validate tokens order - - let operator = false; - for (const part of parts) { - if (part.type === 'operator') { - if (internals.operatorsPrefix.includes(part.value)) { - continue; - } - - if (!operator) { - throw new Error('Formula contains an operator in invalid position'); - } - - if (!internals.operators.includes(part.value)) { - throw new Error(`Formula contains an unknown operator ${part.value}`); - } - } - else if (operator) { - throw new Error('Formula missing expected operator'); - } - - operator = !operator; - } - - if (!operator) { - throw new Error('Formula contains invalid trailing operator'); - } - - // Identify single part - - if (parts.length === 1 && - ['reference', 'literal', 'constant'].includes(parts[0].type)) { - - this.single = { type: parts[0].type === 'reference' ? 'reference' : 'value', value: parts[0].value }; - } - - // Process parts - - this._parts = parts.map((part) => { - - // Operators - - if (part.type === 'operator') { - return internals.operatorsPrefix.includes(part.value) ? part : part.value; - } - - // Literals, constants, segments - - if (part.type !== 'reference') { - return part.value; - } - - // References - - if (this.settings.tokenRx && - !this.settings.tokenRx.test(part.value)) { - - throw new Error(`Formula contains invalid reference ${part.value}`); - } - - if (this.settings.reference) { - return this.settings.reference(part.value); - } - - return internals.reference(part.value); - }); - } - - _subFormula(string, name) { - - const method = this.settings.functions[name]; - if (typeof method !== 'function') { - throw new Error(`Formula contains unknown function ${name}`); - } - - let args = []; - if (string) { - let current = ''; - let parenthesis = 0; - let literal = false; - - const flush = () => { - - if (!current) { - throw new Error(`Formula contains function ${name} with invalid arguments ${string}`); - } - - args.push(current); - current = ''; - }; - - for (let i = 0; i < string.length; ++i) { - const c = string[i]; - if (literal) { - current += c; - if (c === literal) { - literal = false; - } - } - else if (c in internals.literals && - !parenthesis) { - - current += c; - literal = internals.literals[c]; - } - else if (c === ',' && - !parenthesis) { - - flush(); - } - else { - current += c; - if (c === '(') { - ++parenthesis; - } - else if (c === ')') { - --parenthesis; - } - } - } - - flush(); - } - - args = args.map((arg) => new exports.Parser(arg, this.settings)); - - return function (context) { - - const innerValues = []; - for (const arg of args) { - innerValues.push(arg.evaluate(context)); - } - - return method.call(context, ...innerValues); - }; - } - - evaluate(context) { - - const parts = this._parts.slice(); - - // Prefix operators - - for (let i = parts.length - 2; i >= 0; --i) { - const part = parts[i]; - if (part && - part.type === 'operator') { - - const current = parts[i + 1]; - parts.splice(i + 1, 1); - const value = internals.evaluate(current, context); - parts[i] = internals.single(part.value, value); - } - } - - // Left-right operators - - internals.operatorsOrder.forEach((set) => { - - for (let i = 1; i < parts.length - 1;) { - if (set.includes(parts[i])) { - const operator = parts[i]; - const left = internals.evaluate(parts[i - 1], context); - const right = internals.evaluate(parts[i + 1], context); - - parts.splice(i, 2); - const result = internals.calculate(operator, left, right); - parts[i - 1] = result === 0 ? 0 : result; // Convert -0 - } - else { - i += 2; - } - } - }); - - return internals.evaluate(parts[0], context); - } -}; - - -exports.Parser.prototype[internals.symbol] = true; - - -internals.reference = function (name) { - - return function (context) { - - return context && context[name] !== undefined ? context[name] : null; - }; -}; - - -internals.evaluate = function (part, context) { - - if (part === null) { - return null; - } - - if (typeof part === 'function') { - return part(context); - } - - if (part[internals.symbol]) { - return part.evaluate(context); - } - - return part; -}; - - -internals.single = function (operator, value) { - - if (operator === '!') { - return value ? false : true; - } - - // operator === 'n' - - const negative = -value; - if (negative === 0) { // Override -0 - return 0; - } - - return negative; -}; - - -internals.calculate = function (operator, left, right) { - - if (operator === '??') { - return internals.exists(left) ? left : right; - } - - if (typeof left === 'string' || - typeof right === 'string') { - - if (operator === '+') { - left = internals.exists(left) ? left : ''; - right = internals.exists(right) ? right : ''; - return left + right; - } - } - else { - switch (operator) { - case '^': return Math.pow(left, right); - case '*': return left * right; - case '/': return left / right; - case '%': return left % right; - case '+': return left + right; - case '-': return left - right; - } - } - - switch (operator) { - case '<': return left < right; - case '<=': return left <= right; - case '>': return left > right; - case '>=': return left >= right; - case '==': return left === right; - case '!=': return left !== right; - case '&&': return left && right; - case '||': return left || right; - } - - return null; -}; - - -internals.exists = function (value) { - - return value !== null && value !== undefined; -}; - - -/***/ }), - -/***/ 75604: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const internals = {}; - - -exports.location = function (depth = 0) { - - const orig = Error.prepareStackTrace; - Error.prepareStackTrace = (ignore, stack) => stack; - - const capture = {}; - Error.captureStackTrace(capture, this); - const line = capture.stack[depth + 1]; - - Error.prepareStackTrace = orig; - - return { - filename: line.getFileName(), - line: line.getLineNumber() - }; -}; - - -/***/ }), - -/***/ 83682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var register = __nccwpck_require__(44670); -var addHook = __nccwpck_require__(5549); -var removeHook = __nccwpck_require__(6819); - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind; -var bindable = bind.bind(bind); - -function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); -} - -function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {}, - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} - -function HookCollection() { - var state = { - registry: {}, - }; - - var hook = register.bind(null, state); - bindApi(hook, state); - - return hook; -} - -var collectionHookDeprecationMessageDisplayed = false; -function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; - } - return HookCollection(); -} - -Hook.Singular = HookSingular.bind(); -Hook.Collection = HookCollection.bind(); - -module.exports = Hook; -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook; -module.exports.Singular = Hook.Singular; -module.exports.Collection = Hook.Collection; - - -/***/ }), - -/***/ 5549: -/***/ ((module) => { - -module.exports = addHook; - -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } - - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } - - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} - - -/***/ }), - -/***/ 44670: -/***/ ((module) => { - -module.exports = register; - -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - - if (!options) { - options = {}; - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } - - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} - - -/***/ }), - -/***/ 6819: -/***/ ((module) => { - -module.exports = removeHook; + if (signal && signal.aborted) { + abort(); + return; + } -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); + // send request + const req = send(options); + let reqTimeout; - if (index === -1) { - return; - } + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } - state.registry[name].splice(index, 1); -} + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } -/***/ }), + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); -/***/ 6641: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + if (response && response.body) { + destroyStream(response.body, err); + } -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function (module, exports) { - 'use strict'; + finalize(); + }); - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } + if (response && response.body) { + destroyStream(response.body, err); + } + }); - // BN + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } - this.negative = 0; - this.words = null; - this.length = 0; + req.on('response', function (res) { + clearTimeout(reqTimeout); - // Reduction context - this.red = null; + const headers = createHeadersLenient(res.headers); - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } - BN.BN = BN; - BN.wordSize = 26; + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = (__nccwpck_require__(14300).Buffer); - } - } catch (e) { - } + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } - } - } - }; + // HTTP-network fetch step 12.1.1.4: handle content codings - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [number & 0x3ffffff]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } - if (endian !== 'le') return; + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [0]; - this.length = 1; - return this; - } + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this._strip(); - }; + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); - function parseHex4Bits (string, index) { - var c = string.charCodeAt(index); - // '0' - '9' - if (c >= 48 && c <= 57) { - return c - 48; - // 'A' - 'F' - } else if (c >= 65 && c <= 70) { - return c - 55; - // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - } else { - assert(false, 'Invalid character in ' + string); - } - } + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } + request.on('socket', function (s) { + socket = s; + }); - BN.prototype._parseHex = function _parseHex (number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } + request.on('response', function (response) { + const headers = response.headers; - // 24-bits chunks - var off = 0; - var j = 0; + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; - var w; - if (endian === 'be') { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} - this._strip(); - }; +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} - function parseBase (str, start, end, mul) { - var r = 0; - var b = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; - r *= mul; +// expose Promise +fetch.Promise = global.Promise; - // 'a' - if (c >= 49) { - b = c - 49 + 0xa; +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; - // 'A' - } else if (c >= 17) { - b = c - 17 + 0xa; - // '0' - '9' - } else { - b = c; - } - assert(c >= 0 && b < mul, 'Invalid character'); - r += b; - } - return r; - } +/***/ }), - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [0]; - this.length = 1; +/***/ 89891: +/***/ ((__unused_webpack_module, exports) => { - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; +"use strict"; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0; +function assertNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error(`Wrong integer: ${n}`); +} +exports.assertNumber = assertNumber; +function chain(...args) { + const wrap = (a, b) => (c) => a(b(c)); + const encode = Array.from(args) + .reverse() + .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined); + const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined); + return { encode, decode }; +} +function alphabet(alphabet) { + return { + encode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('alphabet.encode input should be an array of numbers'); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet.length) + throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); + return alphabet[i]; + }); + }, + decode: (input) => { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('alphabet.decode input should be array of strings'); + return input.map((letter) => { + if (typeof letter !== 'string') + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet.indexOf(letter); + if (index === -1) + throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); + return index; + }); + }, + }; +} +function join(separator = '') { + if (typeof separator !== 'string') + throw new Error('join separator should be string'); + return { + encode: (from) => { + if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) + throw new Error('join.encode input should be array of strings'); + for (let i of from) + if (typeof i !== 'string') + throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== 'string') + throw new Error('join.decode input should be string'); + return to.split(separator); + }, + }; +} +function padding(bits, chr = '=') { + assertNumber(bits); + if (typeof chr !== 'string') + throw new Error('padding chr should be string'); + return { + encode(data) { + if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of data) + if (typeof i !== 'string') + throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) + data.push(chr); + return data; + }, + decode(input) { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of input) + if (typeof i !== 'string') + throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error('Invalid padding: string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error('Invalid padding: string has too much padding'); + } + return input.slice(0, end); + }, + }; +} +function normalize(fn) { + if (typeof fn !== 'function') + throw new Error('normalize fn should be function'); + return { encode: (from) => from, decode: (to) => fn(to) }; +} +function convertRadix(data, from, to) { + if (from < 2) + throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) + throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) + throw new Error('convertRadix: data should be array'); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) + throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]; + const digitBase = from * carry + digit; + if (!Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry) { + throw new Error('convertRadix: carry overflow'); + } + carry = digitBase % to; + digits[i] = Math.floor(digitBase / to); + if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) + continue; + else if (!digits[i]) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +const gcd = (a, b) => (!b ? a : gcd(b, a % b)); +const radix2carry = (from, to) => from + (to - gcd(from, to)); +function convertRadix2(data, from, to, padding) { + if (!Array.isArray(data)) + throw new Error('convertRadix2: data should be array'); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; + } + carry = (carry << (to - pos)) & mask; + if (!padding && pos >= from) + throw new Error('Excess padding'); + if (!padding && carry) + throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) + res.push(carry >>> 0); + return res; +} +function radix(num) { + assertNumber(num); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), 2 ** 8, num); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix.decode input should be array of strings'); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; +} +function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error('radix2: carry overflow'); + return { + encode: (bytes) => { + if (!(bytes instanceof Uint8Array)) + throw new Error('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix2.decode input should be array of strings'); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} +function unsafeWrapper(fn) { + if (typeof fn !== 'function') + throw new Error('unsafeWrapper fn should be function'); + return function (...args) { + try { + return fn.apply(null, args); + } + catch (e) { } + }; +} +function checksum(len, fn) { + assertNumber(len); + if (typeof fn !== 'function') + throw new Error('checksum fn should be function'); + return { + encode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.encode: input should be Uint8Array'); + const checksum = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum, data.length); + return res; + }, + decode(data) { + if (!(data instanceof Uint8Array)) + throw new Error('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error('Invalid checksum'); + return payload; + }, + }; +} +exports.utils = { alphabet, chain, checksum, radix, radix2, join, padding }; +exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); +exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); +exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); +exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); +exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); +exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')); +const genBase58 = (abc) => chain(radix(58), alphabet(abc), join('')); +exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); +exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'); +exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'); +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +exports.base58xmr = { + encode(data) { + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); + } + return res; + }, + decode(str) { + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = exports.base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}; +const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58); +exports.base58check = base58check; +const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) + chk ^= POLYMOD_GENERATORS[i]; + } + return chk; +} +function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) + chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); +} +function genBech32(encoding) { + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + if (typeof prefix !== 'string') + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + prefix = prefix.toLowerCase(); + return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; + } + function decode(str, limit = 90) { + if (typeof str !== 'string') + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = str.slice(0, sepIndex); + const _words = str.slice(sepIndex + 1); + if (_words.length < 6) + throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(_words).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode); + function decodeToBytes(str) { + const { prefix, words } = decode(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; +} +exports.bech32 = genBech32('bech32'); +exports.bech32m = genBech32('bech32m'); +exports.utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), +}; +exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { + if (typeof s !== 'string' || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); +})); +const CODERS = { + utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr +}; +const coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`; +const bytesToString = (type, bytes) => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (!(bytes instanceof Uint8Array)) + throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +exports.bytesToString = bytesToString; +exports.str = exports.bytesToString; +const stringToBytes = (type, str) => { + if (!CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (typeof str !== 'string') + throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +exports.stringToBytes = stringToBytes; +exports.bytes = exports.stringToBytes; - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } +/***/ }), - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); +/***/ 97425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (i = 0; i < mod; i++) { - pow *= base; - } +"use strict"; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - this._strip(); - }; +const Url = __nccwpck_require__(57310); - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; +const Errors = __nccwpck_require__(91594); - function move (dest, src) { - dest.words = src.words; - dest.length = src.length; - dest.negative = src.negative; - dest.red = src.red; - } - BN.prototype._move = function _move (dest) { - move(dest, this); - }; +const internals = { + minDomainSegments: 2, + nonAsciiRx: /[^\x00-\x7f]/, + domainControlRx: /[\x00-\x20@\:\/\\#!\$&\'\(\)\*\+,;=\?]/, // Control + space + separators + tldSegmentRx: /^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, + domainSegmentRx: /^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, + URL: Url.URL || URL // $lab:coverage:ignore$ +}; - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; +exports.analyze = function (domain, options = {}) { - // Remove leading `0` from `this` - BN.prototype._strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; + if (!domain) { // Catch null / undefined + return Errors.code('DOMAIN_NON_EMPTY_STRING'); } - return this._normSign(); - }; - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; + if (typeof domain !== 'string') { + throw new Error('Invalid input: domain must be a string'); } - return this; - }; - // Check Symbol.for because not everywhere where Symbol defined - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility - if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { - try { - BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; - } catch (e) { - BN.prototype.inspect = inspect; + if (domain.length > 256) { + return Errors.code('DOMAIN_TOO_LONG'); } - } else { - BN.prototype.inspect = inspect; - } - - function inspect () { - return (this.red ? ''; - } - - /* - var zeros = []; - var groupSizes = []; - var groupBases = []; + const ascii = !internals.nonAsciiRx.test(domain); + if (!ascii) { + if (options.allowUnicode === false) { // Defaults to true + return Errors.code('DOMAIN_INVALID_UNICODE_CHARS'); + } - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; + domain = domain.normalize('NFC'); } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; + if (internals.domainControlRx.test(domain)) { + return Errors.code('DOMAIN_INVALID_CHARS'); + } - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; + domain = internals.punycode(domain); - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; + // https://tools.ietf.org/html/rfc1035 section 2.3.1 - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; + if (options.allowFullyQualified && + domain[domain.length - 1] === '.') { - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; + domain = domain.slice(0, -1); } - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modrn(groupBase).toString(base); - c = c.idivn(groupBase); + const minDomainSegments = options.minDomainSegments || internals.minDomainSegments; - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; + const segments = domain.split('.'); + if (segments.length < minDomainSegments) { + return Errors.code('DOMAIN_SEGMENTS_COUNT'); } - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); + if (options.maxDomainSegments) { + if (segments.length > options.maxDomainSegments) { + return Errors.code('DOMAIN_SEGMENTS_COUNT_MAX'); + } } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16, 2); - }; - - if (Buffer) { - BN.prototype.toBuffer = function toBuffer (endian, length) { - return this.toArrayLike(Buffer, endian, length); - }; - } - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; + const tlds = options.tlds; + if (tlds) { + const tld = segments[segments.length - 1].toLowerCase(); + if (tlds.deny && tlds.deny.has(tld) || + tlds.allow && !tlds.allow.has(tld)) { - var allocate = function allocate (ArrayType, size) { - if (ArrayType.allocUnsafe) { - return ArrayType.allocUnsafe(size); + return Errors.code('DOMAIN_FORBIDDEN_TLDS'); + } } - return new ArrayType(size); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - this._strip(); - - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - var res = allocate(ArrayType, reqLength); - var postfix = endian === 'le' ? 'LE' : 'BE'; - this['_toArrayLike' + postfix](res, byteLength); - return res; - }; - BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { - var position = 0; - var carry = 0; + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; - for (var i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; + if (!segment.length) { + return Errors.code('DOMAIN_EMPTY_SEGMENT'); + } - res[position++] = word & 0xff; - if (position < res.length) { - res[position++] = (word >> 8) & 0xff; - } - if (position < res.length) { - res[position++] = (word >> 16) & 0xff; - } + if (segment.length > 63) { + return Errors.code('DOMAIN_LONG_SEGMENT'); + } - if (shift === 6) { - if (position < res.length) { - res[position++] = (word >> 24) & 0xff; + if (i < segments.length - 1) { + if (!internals.domainSegmentRx.test(segment)) { + return Errors.code('DOMAIN_INVALID_CHARS'); + } + } + else { + if (!internals.tldSegmentRx.test(segment)) { + return Errors.code('DOMAIN_INVALID_TLDS_CHARS'); + } } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } } - if (position < res.length) { - res[position++] = carry; - - while (position < res.length) { - res[position++] = 0; - } - } - }; + return null; +}; - BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { - var position = res.length - 1; - var carry = 0; - for (var i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; +exports.isValid = function (domain, options) { - res[position--] = word & 0xff; - if (position >= 0) { - res[position--] = (word >> 8) & 0xff; - } - if (position >= 0) { - res[position--] = (word >> 16) & 0xff; - } + return !exports.analyze(domain, options); +}; - if (shift === 6) { - if (position >= 0) { - res[position--] = (word >> 24) & 0xff; - } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } - if (position >= 0) { - res[position--] = carry; +internals.punycode = function (domain) { - while (position >= 0) { - res[position--] = 0; - } + if (domain.includes('%')) { + domain = domain.replace(/%/g, '%25'); } - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; + try { + return new internals.URL(`http://${domain}`).host; } - if ((t & 0x1) === 0) { - r++; + catch (err) { + return domain; } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; +}; - w[bit] = (num.words[off] >>> wbit) & 0x01; - } - return w; - } +/***/ }), - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; +/***/ 3283: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; +"use strict"; - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; +const Util = __nccwpck_require__(73837); - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; +const Domain = __nccwpck_require__(97425); +const Errors = __nccwpck_require__(91594); - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; +const internals = { + nonAsciiRx: /[^\x00-\x7f]/, + encoder: new (Util.TextEncoder || TextEncoder)() // $lab:coverage:ignore$ +}; - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - return this; - }; +exports.analyze = function (email, options) { - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + return internals.email(email, options); +}; - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - return this._strip(); - }; +exports.isValid = function (email, options) { - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; + return !internals.email(email, options); +}; - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; +internals.email = function (email, options = {}) { - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; + if (typeof email !== 'string') { + throw new Error('Invalid input: email must be a string'); } - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + if (!email) { + return Errors.code('EMPTY_STRING'); } - this.length = b.length; - - return this._strip(); - }; + // Unicode - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + const ascii = !internals.nonAsciiRx.test(email); + if (!ascii) { + if (options.allowUnicode === false) { // Defaults to true + return Errors.code('FORBIDDEN_UNICODE'); + } - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; + email = email.normalize('NFC'); + } - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + // Basic structure - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + const parts = email.split('@'); + if (parts.length !== 2) { + return parts.length > 2 ? Errors.code('MULTIPLE_AT_CHAR') : Errors.code('MISSING_AT_CHAR'); } - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + const [local, domain] = parts; + + if (!local) { + return Errors.code('EMPTY_LOCAL'); } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + if (!options.ignoreLength) { + if (email.length > 254) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3 + return Errors.code('ADDRESS_TOO_LONG'); + } + + if (internals.encoder.encode(local).length > 64) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 + return Errors.code('LOCAL_TOO_LONG'); + } } - this.length = a.length; + // Validate parts - return this._strip(); - }; + return internals.local(local, ascii) || Domain.analyze(domain, options); +}; - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; +internals.local = function (local, ascii) { - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + const segments = local.split('.'); + for (const segment of segments) { + if (!segment.length) { + return Errors.code('EMPTY_LOCAL_SEGMENT'); + } - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + if (ascii) { + if (!internals.atextRx.test(segment)) { + return Errors.code('INVALID_LOCAL_CHARS'); + } - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + continue; + } - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); + for (const char of segment) { + if (internals.atextRx.test(char)) { + continue; + } - if (bitsLeft > 0) { - bytesNeeded--; + const binary = internals.binary(char); + if (!internals.atomRx.test(binary)) { + return Errors.code('INVALID_LOCAL_CHARS'); + } + } } +}; - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } +internals.binary = function (char) { - // And remove leading zeroes - return this._strip(); - }; + return Array.from(internals.encoder.encode(char)).map((v) => String.fromCharCode(v)).join(''); +}; - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); +/* + From RFC 5321: - var off = (bit / 26) | 0; - var wbit = bit % 26; + Mailbox = Local-part "@" ( Domain / address-literal ) - this._expand(off + 1); + Local-part = Dot-string / Quoted-string + Dot-string = Atom *("." Atom) + Atom = 1*atext + atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } + Domain = sub-domain *("." sub-domain) + sub-domain = Let-dig [Ldh-str] + Let-dig = ALPHA / DIGIT + Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig - return this._strip(); - }; + ALPHA = %x41-5A / %x61-7A ; a-z, A-Z + DIGIT = %x30-39 ; 0-9 - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + From RFC 6531: - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + sub-domain =/ U-label + atext =/ UTF8-non-ascii - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } + UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + UTF8-2 = %xC2-DF UTF8-tail + UTF8-3 = %xE0 %xA0-BF UTF8-tail / + %xE1-EC 2( UTF8-tail ) / + %xED %x80-9F UTF8-tail / + %xEE-EF 2( UTF8-tail ) + UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / + %xF1-F3 3( UTF8-tail ) / + %xF4 %x80-8F 2( UTF8-tail ) - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } + UTF8-tail = %x80-BF - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + Note: The following are not supported: - return this; - }; + RFC 5321: address-literal, Quoted-string + RFC 5322: obs-*, CFWS +*/ - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - if (this.length > num.length) return this.clone().iadd(num); +internals.atextRx = /^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/; // _ included in \w - return num.clone().iadd(this); - }; - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); +internals.atomRx = new RegExp([ - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + // %xC2-DF UTF8-tail + '(?:[\\xc2-\\xdf][\\x80-\\xbf])', - // At this point both numbers are positive - var cmp = this.cmp(num); + // %xE0 %xA0-BF UTF8-tail %xE1-EC 2( UTF8-tail ) %xED %x80-9F UTF8-tail %xEE-EF 2( UTF8-tail ) + '(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})', - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + // %xF0 %x90-BF 2( UTF8-tail ) %xF1-F3 3( UTF8-tail ) %xF4 %x80-8F 2( UTF8-tail ) + '(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})' - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } +].join('|')); - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } +/***/ }), - this.length = Math.max(this.length, i); +/***/ 91594: +/***/ ((__unused_webpack_module, exports) => { - if (a !== this) { - this.negative = 1; - } +"use strict"; - return this._strip(); - }; - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; +exports.codes = { + EMPTY_STRING: 'Address must be a non-empty string', + FORBIDDEN_UNICODE: 'Address contains forbidden Unicode characters', + MULTIPLE_AT_CHAR: 'Address cannot contain more than one @ character', + MISSING_AT_CHAR: 'Address must contain one @ character', + EMPTY_LOCAL: 'Address local part cannot be empty', + ADDRESS_TOO_LONG: 'Address too long', + LOCAL_TOO_LONG: 'Address local part too long', + EMPTY_LOCAL_SEGMENT: 'Address local part contains empty dot-separated segment', + INVALID_LOCAL_CHARS: 'Address local part contains invalid character', + DOMAIN_NON_EMPTY_STRING: 'Domain must be a non-empty string', + DOMAIN_TOO_LONG: 'Domain too long', + DOMAIN_INVALID_UNICODE_CHARS: 'Domain contains forbidden Unicode characters', + DOMAIN_INVALID_CHARS: 'Domain contains invalid character', + DOMAIN_INVALID_TLDS_CHARS: 'Domain contains invalid tld character', + DOMAIN_SEGMENTS_COUNT: 'Domain lacks the minimum required number of segments', + DOMAIN_SEGMENTS_COUNT_MAX: 'Domain contains too many segments', + DOMAIN_FORBIDDEN_TLDS: 'Domain uses forbidden TLD', + DOMAIN_EMPTY_SEGMENT: 'Domain contains empty dot-separated segment', + DOMAIN_LONG_SEGMENT: 'Domain contains dot-separated segment that is too long' +}; - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; +exports.code = function (code) { - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; + return { code, error: exports.codes[code] }; +}; - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - return out._strip(); - } +/***/ }), + +/***/ 82337: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); + +const Uri = __nccwpck_require__(74983); + + +const internals = {}; - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; +exports.regex = function (options = {}) { + + // CIDR + + Assert(options.cidr === undefined || typeof options.cidr === 'string', 'options.cidr must be a string'); + const cidr = options.cidr ? options.cidr.toLowerCase() : 'optional'; + Assert(['required', 'optional', 'forbidden'].includes(cidr), 'options.cidr must be one of required, optional, forbidden'); + + // Versions + + Assert(options.version === undefined || typeof options.version === 'string' || Array.isArray(options.version), 'options.version must be a string or an array of string'); + let versions = options.version || ['ipv4', 'ipv6', 'ipvfuture']; + if (!Array.isArray(versions)) { + versions = [versions]; } - return out; - }; - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } + Assert(versions.length >= 1, 'options.version must have at least 1 version specified'); - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; + for (let i = 0; i < versions.length; ++i) { + Assert(typeof versions[i] === 'string', 'options.version must only contain strings'); + versions[i] = versions[i].toLowerCase(); + Assert(['ipv4', 'ipv6', 'ipvfuture'].includes(versions[i]), 'options.version contains unknown version ' + versions[i] + ' - must be one of ipv4, ipv6, ipvfuture'); + } - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; + versions = Array.from(new Set(versions)); - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; + // Regex - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } + const parts = versions.map((version) => { - return out._strip(); - } + // Forbidden - function jumboMulTo (self, num, out) { - // Temporary disable, see https://github.com/indutny/bn.js/issues/211 - // var fftm = new FFTM(); - // return fftm.mulp(self, num, out); - return bigMulTo(self, num, out); - } + if (cidr === 'forbidden') { + return Uri.ip[version]; + } - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } + // Required - return res; - }; + const cidrpart = `\\/${version === 'ipv4' ? Uri.ip.v4Cidr : Uri.ip.v6Cidr}`; + + if (cidr === 'required') { + return `${Uri.ip[version]}${cidrpart}`; + } + + // Optional + + return `${Uri.ip[version]}(?:${cidrpart})?`; + }); + + const raw = `(?:${parts.join('|')})`; + const regex = new RegExp(`^${raw}$`); + return { cidr, versions, regex, raw }; +}; + + +/***/ }), + +/***/ 53092: +/***/ ((module) => { + +"use strict"; + + +const internals = {}; + + +// http://data.iana.org/TLD/tlds-alpha-by-domain.txt +// # Version 2024012900, Last Updated Mon Jan 29 07:07:01 2024 UTC + + +internals.tlds = [ + 'AAA', + 'AARP', + 'ABB', + 'ABBOTT', + 'ABBVIE', + 'ABC', + 'ABLE', + 'ABOGADO', + 'ABUDHABI', + 'AC', + 'ACADEMY', + 'ACCENTURE', + 'ACCOUNTANT', + 'ACCOUNTANTS', + 'ACO', + 'ACTOR', + 'AD', + 'ADS', + 'ADULT', + 'AE', + 'AEG', + 'AERO', + 'AETNA', + 'AF', + 'AFL', + 'AFRICA', + 'AG', + 'AGAKHAN', + 'AGENCY', + 'AI', + 'AIG', + 'AIRBUS', + 'AIRFORCE', + 'AIRTEL', + 'AKDN', + 'AL', + 'ALIBABA', + 'ALIPAY', + 'ALLFINANZ', + 'ALLSTATE', + 'ALLY', + 'ALSACE', + 'ALSTOM', + 'AM', + 'AMAZON', + 'AMERICANEXPRESS', + 'AMERICANFAMILY', + 'AMEX', + 'AMFAM', + 'AMICA', + 'AMSTERDAM', + 'ANALYTICS', + 'ANDROID', + 'ANQUAN', + 'ANZ', + 'AO', + 'AOL', + 'APARTMENTS', + 'APP', + 'APPLE', + 'AQ', + 'AQUARELLE', + 'AR', + 'ARAB', + 'ARAMCO', + 'ARCHI', + 'ARMY', + 'ARPA', + 'ART', + 'ARTE', + 'AS', + 'ASDA', + 'ASIA', + 'ASSOCIATES', + 'AT', + 'ATHLETA', + 'ATTORNEY', + 'AU', + 'AUCTION', + 'AUDI', + 'AUDIBLE', + 'AUDIO', + 'AUSPOST', + 'AUTHOR', + 'AUTO', + 'AUTOS', + 'AVIANCA', + 'AW', + 'AWS', + 'AX', + 'AXA', + 'AZ', + 'AZURE', + 'BA', + 'BABY', + 'BAIDU', + 'BANAMEX', + 'BAND', + 'BANK', + 'BAR', + 'BARCELONA', + 'BARCLAYCARD', + 'BARCLAYS', + 'BAREFOOT', + 'BARGAINS', + 'BASEBALL', + 'BASKETBALL', + 'BAUHAUS', + 'BAYERN', + 'BB', + 'BBC', + 'BBT', + 'BBVA', + 'BCG', + 'BCN', + 'BD', + 'BE', + 'BEATS', + 'BEAUTY', + 'BEER', + 'BENTLEY', + 'BERLIN', + 'BEST', + 'BESTBUY', + 'BET', + 'BF', + 'BG', + 'BH', + 'BHARTI', + 'BI', + 'BIBLE', + 'BID', + 'BIKE', + 'BING', + 'BINGO', + 'BIO', + 'BIZ', + 'BJ', + 'BLACK', + 'BLACKFRIDAY', + 'BLOCKBUSTER', + 'BLOG', + 'BLOOMBERG', + 'BLUE', + 'BM', + 'BMS', + 'BMW', + 'BN', + 'BNPPARIBAS', + 'BO', + 'BOATS', + 'BOEHRINGER', + 'BOFA', + 'BOM', + 'BOND', + 'BOO', + 'BOOK', + 'BOOKING', + 'BOSCH', + 'BOSTIK', + 'BOSTON', + 'BOT', + 'BOUTIQUE', + 'BOX', + 'BR', + 'BRADESCO', + 'BRIDGESTONE', + 'BROADWAY', + 'BROKER', + 'BROTHER', + 'BRUSSELS', + 'BS', + 'BT', + 'BUILD', + 'BUILDERS', + 'BUSINESS', + 'BUY', + 'BUZZ', + 'BV', + 'BW', + 'BY', + 'BZ', + 'BZH', + 'CA', + 'CAB', + 'CAFE', + 'CAL', + 'CALL', + 'CALVINKLEIN', + 'CAM', + 'CAMERA', + 'CAMP', + 'CANON', + 'CAPETOWN', + 'CAPITAL', + 'CAPITALONE', + 'CAR', + 'CARAVAN', + 'CARDS', + 'CARE', + 'CAREER', + 'CAREERS', + 'CARS', + 'CASA', + 'CASE', + 'CASH', + 'CASINO', + 'CAT', + 'CATERING', + 'CATHOLIC', + 'CBA', + 'CBN', + 'CBRE', + 'CC', + 'CD', + 'CENTER', + 'CEO', + 'CERN', + 'CF', + 'CFA', + 'CFD', + 'CG', + 'CH', + 'CHANEL', + 'CHANNEL', + 'CHARITY', + 'CHASE', + 'CHAT', + 'CHEAP', + 'CHINTAI', + 'CHRISTMAS', + 'CHROME', + 'CHURCH', + 'CI', + 'CIPRIANI', + 'CIRCLE', + 'CISCO', + 'CITADEL', + 'CITI', + 'CITIC', + 'CITY', + 'CK', + 'CL', + 'CLAIMS', + 'CLEANING', + 'CLICK', + 'CLINIC', + 'CLINIQUE', + 'CLOTHING', + 'CLOUD', + 'CLUB', + 'CLUBMED', + 'CM', + 'CN', + 'CO', + 'COACH', + 'CODES', + 'COFFEE', + 'COLLEGE', + 'COLOGNE', + 'COM', + 'COMCAST', + 'COMMBANK', + 'COMMUNITY', + 'COMPANY', + 'COMPARE', + 'COMPUTER', + 'COMSEC', + 'CONDOS', + 'CONSTRUCTION', + 'CONSULTING', + 'CONTACT', + 'CONTRACTORS', + 'COOKING', + 'COOL', + 'COOP', + 'CORSICA', + 'COUNTRY', + 'COUPON', + 'COUPONS', + 'COURSES', + 'CPA', + 'CR', + 'CREDIT', + 'CREDITCARD', + 'CREDITUNION', + 'CRICKET', + 'CROWN', + 'CRS', + 'CRUISE', + 'CRUISES', + 'CU', + 'CUISINELLA', + 'CV', + 'CW', + 'CX', + 'CY', + 'CYMRU', + 'CYOU', + 'CZ', + 'DABUR', + 'DAD', + 'DANCE', + 'DATA', + 'DATE', + 'DATING', + 'DATSUN', + 'DAY', + 'DCLK', + 'DDS', + 'DE', + 'DEAL', + 'DEALER', + 'DEALS', + 'DEGREE', + 'DELIVERY', + 'DELL', + 'DELOITTE', + 'DELTA', + 'DEMOCRAT', + 'DENTAL', + 'DENTIST', + 'DESI', + 'DESIGN', + 'DEV', + 'DHL', + 'DIAMONDS', + 'DIET', + 'DIGITAL', + 'DIRECT', + 'DIRECTORY', + 'DISCOUNT', + 'DISCOVER', + 'DISH', + 'DIY', + 'DJ', + 'DK', + 'DM', + 'DNP', + 'DO', + 'DOCS', + 'DOCTOR', + 'DOG', + 'DOMAINS', + 'DOT', + 'DOWNLOAD', + 'DRIVE', + 'DTV', + 'DUBAI', + 'DUNLOP', + 'DUPONT', + 'DURBAN', + 'DVAG', + 'DVR', + 'DZ', + 'EARTH', + 'EAT', + 'EC', + 'ECO', + 'EDEKA', + 'EDU', + 'EDUCATION', + 'EE', + 'EG', + 'EMAIL', + 'EMERCK', + 'ENERGY', + 'ENGINEER', + 'ENGINEERING', + 'ENTERPRISES', + 'EPSON', + 'EQUIPMENT', + 'ER', + 'ERICSSON', + 'ERNI', + 'ES', + 'ESQ', + 'ESTATE', + 'ET', + 'EU', + 'EUROVISION', + 'EUS', + 'EVENTS', + 'EXCHANGE', + 'EXPERT', + 'EXPOSED', + 'EXPRESS', + 'EXTRASPACE', + 'FAGE', + 'FAIL', + 'FAIRWINDS', + 'FAITH', + 'FAMILY', + 'FAN', + 'FANS', + 'FARM', + 'FARMERS', + 'FASHION', + 'FAST', + 'FEDEX', + 'FEEDBACK', + 'FERRARI', + 'FERRERO', + 'FI', + 'FIDELITY', + 'FIDO', + 'FILM', + 'FINAL', + 'FINANCE', + 'FINANCIAL', + 'FIRE', + 'FIRESTONE', + 'FIRMDALE', + 'FISH', + 'FISHING', + 'FIT', + 'FITNESS', + 'FJ', + 'FK', + 'FLICKR', + 'FLIGHTS', + 'FLIR', + 'FLORIST', + 'FLOWERS', + 'FLY', + 'FM', + 'FO', + 'FOO', + 'FOOD', + 'FOOTBALL', + 'FORD', + 'FOREX', + 'FORSALE', + 'FORUM', + 'FOUNDATION', + 'FOX', + 'FR', + 'FREE', + 'FRESENIUS', + 'FRL', + 'FROGANS', + 'FRONTIER', + 'FTR', + 'FUJITSU', + 'FUN', + 'FUND', + 'FURNITURE', + 'FUTBOL', + 'FYI', + 'GA', + 'GAL', + 'GALLERY', + 'GALLO', + 'GALLUP', + 'GAME', + 'GAMES', + 'GAP', + 'GARDEN', + 'GAY', + 'GB', + 'GBIZ', + 'GD', + 'GDN', + 'GE', + 'GEA', + 'GENT', + 'GENTING', + 'GEORGE', + 'GF', + 'GG', + 'GGEE', + 'GH', + 'GI', + 'GIFT', + 'GIFTS', + 'GIVES', + 'GIVING', + 'GL', + 'GLASS', + 'GLE', + 'GLOBAL', + 'GLOBO', + 'GM', + 'GMAIL', + 'GMBH', + 'GMO', + 'GMX', + 'GN', + 'GODADDY', + 'GOLD', + 'GOLDPOINT', + 'GOLF', + 'GOO', + 'GOODYEAR', + 'GOOG', + 'GOOGLE', + 'GOP', + 'GOT', + 'GOV', + 'GP', + 'GQ', + 'GR', + 'GRAINGER', + 'GRAPHICS', + 'GRATIS', + 'GREEN', + 'GRIPE', + 'GROCERY', + 'GROUP', + 'GS', + 'GT', + 'GU', + 'GUARDIAN', + 'GUCCI', + 'GUGE', + 'GUIDE', + 'GUITARS', + 'GURU', + 'GW', + 'GY', + 'HAIR', + 'HAMBURG', + 'HANGOUT', + 'HAUS', + 'HBO', + 'HDFC', + 'HDFCBANK', + 'HEALTH', + 'HEALTHCARE', + 'HELP', + 'HELSINKI', + 'HERE', + 'HERMES', + 'HIPHOP', + 'HISAMITSU', + 'HITACHI', + 'HIV', + 'HK', + 'HKT', + 'HM', + 'HN', + 'HOCKEY', + 'HOLDINGS', + 'HOLIDAY', + 'HOMEDEPOT', + 'HOMEGOODS', + 'HOMES', + 'HOMESENSE', + 'HONDA', + 'HORSE', + 'HOSPITAL', + 'HOST', + 'HOSTING', + 'HOT', + 'HOTELS', + 'HOTMAIL', + 'HOUSE', + 'HOW', + 'HR', + 'HSBC', + 'HT', + 'HU', + 'HUGHES', + 'HYATT', + 'HYUNDAI', + 'IBM', + 'ICBC', + 'ICE', + 'ICU', + 'ID', + 'IE', + 'IEEE', + 'IFM', + 'IKANO', + 'IL', + 'IM', + 'IMAMAT', + 'IMDB', + 'IMMO', + 'IMMOBILIEN', + 'IN', + 'INC', + 'INDUSTRIES', + 'INFINITI', + 'INFO', + 'ING', + 'INK', + 'INSTITUTE', + 'INSURANCE', + 'INSURE', + 'INT', + 'INTERNATIONAL', + 'INTUIT', + 'INVESTMENTS', + 'IO', + 'IPIRANGA', + 'IQ', + 'IR', + 'IRISH', + 'IS', + 'ISMAILI', + 'IST', + 'ISTANBUL', + 'IT', + 'ITAU', + 'ITV', + 'JAGUAR', + 'JAVA', + 'JCB', + 'JE', + 'JEEP', + 'JETZT', + 'JEWELRY', + 'JIO', + 'JLL', + 'JM', + 'JMP', + 'JNJ', + 'JO', + 'JOBS', + 'JOBURG', + 'JOT', + 'JOY', + 'JP', + 'JPMORGAN', + 'JPRS', + 'JUEGOS', + 'JUNIPER', + 'KAUFEN', + 'KDDI', + 'KE', + 'KERRYHOTELS', + 'KERRYLOGISTICS', + 'KERRYPROPERTIES', + 'KFH', + 'KG', + 'KH', + 'KI', + 'KIA', + 'KIDS', + 'KIM', + 'KINDLE', + 'KITCHEN', + 'KIWI', + 'KM', + 'KN', + 'KOELN', + 'KOMATSU', + 'KOSHER', + 'KP', + 'KPMG', + 'KPN', + 'KR', + 'KRD', + 'KRED', + 'KUOKGROUP', + 'KW', + 'KY', + 'KYOTO', + 'KZ', + 'LA', + 'LACAIXA', + 'LAMBORGHINI', + 'LAMER', + 'LANCASTER', + 'LAND', + 'LANDROVER', + 'LANXESS', + 'LASALLE', + 'LAT', + 'LATINO', + 'LATROBE', + 'LAW', + 'LAWYER', + 'LB', + 'LC', + 'LDS', + 'LEASE', + 'LECLERC', + 'LEFRAK', + 'LEGAL', + 'LEGO', + 'LEXUS', + 'LGBT', + 'LI', + 'LIDL', + 'LIFE', + 'LIFEINSURANCE', + 'LIFESTYLE', + 'LIGHTING', + 'LIKE', + 'LILLY', + 'LIMITED', + 'LIMO', + 'LINCOLN', + 'LINK', + 'LIPSY', + 'LIVE', + 'LIVING', + 'LK', + 'LLC', + 'LLP', + 'LOAN', + 'LOANS', + 'LOCKER', + 'LOCUS', + 'LOL', + 'LONDON', + 'LOTTE', + 'LOTTO', + 'LOVE', + 'LPL', + 'LPLFINANCIAL', + 'LR', + 'LS', + 'LT', + 'LTD', + 'LTDA', + 'LU', + 'LUNDBECK', + 'LUXE', + 'LUXURY', + 'LV', + 'LY', + 'MA', + 'MADRID', + 'MAIF', + 'MAISON', + 'MAKEUP', + 'MAN', + 'MANAGEMENT', + 'MANGO', + 'MAP', + 'MARKET', + 'MARKETING', + 'MARKETS', + 'MARRIOTT', + 'MARSHALLS', + 'MATTEL', + 'MBA', + 'MC', + 'MCKINSEY', + 'MD', + 'ME', + 'MED', + 'MEDIA', + 'MEET', + 'MELBOURNE', + 'MEME', + 'MEMORIAL', + 'MEN', + 'MENU', + 'MERCKMSD', + 'MG', + 'MH', + 'MIAMI', + 'MICROSOFT', + 'MIL', + 'MINI', + 'MINT', + 'MIT', + 'MITSUBISHI', + 'MK', + 'ML', + 'MLB', + 'MLS', + 'MM', + 'MMA', + 'MN', + 'MO', + 'MOBI', + 'MOBILE', + 'MODA', + 'MOE', + 'MOI', + 'MOM', + 'MONASH', + 'MONEY', + 'MONSTER', + 'MORMON', + 'MORTGAGE', + 'MOSCOW', + 'MOTO', + 'MOTORCYCLES', + 'MOV', + 'MOVIE', + 'MP', + 'MQ', + 'MR', + 'MS', + 'MSD', + 'MT', + 'MTN', + 'MTR', + 'MU', + 'MUSEUM', + 'MUSIC', + 'MV', + 'MW', + 'MX', + 'MY', + 'MZ', + 'NA', + 'NAB', + 'NAGOYA', + 'NAME', + 'NATURA', + 'NAVY', + 'NBA', + 'NC', + 'NE', + 'NEC', + 'NET', + 'NETBANK', + 'NETFLIX', + 'NETWORK', + 'NEUSTAR', + 'NEW', + 'NEWS', + 'NEXT', + 'NEXTDIRECT', + 'NEXUS', + 'NF', + 'NFL', + 'NG', + 'NGO', + 'NHK', + 'NI', + 'NICO', + 'NIKE', + 'NIKON', + 'NINJA', + 'NISSAN', + 'NISSAY', + 'NL', + 'NO', + 'NOKIA', + 'NORTON', + 'NOW', + 'NOWRUZ', + 'NOWTV', + 'NP', + 'NR', + 'NRA', + 'NRW', + 'NTT', + 'NU', + 'NYC', + 'NZ', + 'OBI', + 'OBSERVER', + 'OFFICE', + 'OKINAWA', + 'OLAYAN', + 'OLAYANGROUP', + 'OLLO', + 'OM', + 'OMEGA', + 'ONE', + 'ONG', + 'ONL', + 'ONLINE', + 'OOO', + 'OPEN', + 'ORACLE', + 'ORANGE', + 'ORG', + 'ORGANIC', + 'ORIGINS', + 'OSAKA', + 'OTSUKA', + 'OTT', + 'OVH', + 'PA', + 'PAGE', + 'PANASONIC', + 'PARIS', + 'PARS', + 'PARTNERS', + 'PARTS', + 'PARTY', + 'PAY', + 'PCCW', + 'PE', + 'PET', + 'PF', + 'PFIZER', + 'PG', + 'PH', + 'PHARMACY', + 'PHD', + 'PHILIPS', + 'PHONE', + 'PHOTO', + 'PHOTOGRAPHY', + 'PHOTOS', + 'PHYSIO', + 'PICS', + 'PICTET', + 'PICTURES', + 'PID', + 'PIN', + 'PING', + 'PINK', + 'PIONEER', + 'PIZZA', + 'PK', + 'PL', + 'PLACE', + 'PLAY', + 'PLAYSTATION', + 'PLUMBING', + 'PLUS', + 'PM', + 'PN', + 'PNC', + 'POHL', + 'POKER', + 'POLITIE', + 'PORN', + 'POST', + 'PR', + 'PRAMERICA', + 'PRAXI', + 'PRESS', + 'PRIME', + 'PRO', + 'PROD', + 'PRODUCTIONS', + 'PROF', + 'PROGRESSIVE', + 'PROMO', + 'PROPERTIES', + 'PROPERTY', + 'PROTECTION', + 'PRU', + 'PRUDENTIAL', + 'PS', + 'PT', + 'PUB', + 'PW', + 'PWC', + 'PY', + 'QA', + 'QPON', + 'QUEBEC', + 'QUEST', + 'RACING', + 'RADIO', + 'RE', + 'READ', + 'REALESTATE', + 'REALTOR', + 'REALTY', + 'RECIPES', + 'RED', + 'REDSTONE', + 'REDUMBRELLA', + 'REHAB', + 'REISE', + 'REISEN', + 'REIT', + 'RELIANCE', + 'REN', + 'RENT', + 'RENTALS', + 'REPAIR', + 'REPORT', + 'REPUBLICAN', + 'REST', + 'RESTAURANT', + 'REVIEW', + 'REVIEWS', + 'REXROTH', + 'RICH', + 'RICHARDLI', + 'RICOH', + 'RIL', + 'RIO', + 'RIP', + 'RO', + 'ROCKS', + 'RODEO', + 'ROGERS', + 'ROOM', + 'RS', + 'RSVP', + 'RU', + 'RUGBY', + 'RUHR', + 'RUN', + 'RW', + 'RWE', + 'RYUKYU', + 'SA', + 'SAARLAND', + 'SAFE', + 'SAFETY', + 'SAKURA', + 'SALE', + 'SALON', + 'SAMSCLUB', + 'SAMSUNG', + 'SANDVIK', + 'SANDVIKCOROMANT', + 'SANOFI', + 'SAP', + 'SARL', + 'SAS', + 'SAVE', + 'SAXO', + 'SB', + 'SBI', + 'SBS', + 'SC', + 'SCB', + 'SCHAEFFLER', + 'SCHMIDT', + 'SCHOLARSHIPS', + 'SCHOOL', + 'SCHULE', + 'SCHWARZ', + 'SCIENCE', + 'SCOT', + 'SD', + 'SE', + 'SEARCH', + 'SEAT', + 'SECURE', + 'SECURITY', + 'SEEK', + 'SELECT', + 'SENER', + 'SERVICES', + 'SEVEN', + 'SEW', + 'SEX', + 'SEXY', + 'SFR', + 'SG', + 'SH', + 'SHANGRILA', + 'SHARP', + 'SHAW', + 'SHELL', + 'SHIA', + 'SHIKSHA', + 'SHOES', + 'SHOP', + 'SHOPPING', + 'SHOUJI', + 'SHOW', + 'SI', + 'SILK', + 'SINA', + 'SINGLES', + 'SITE', + 'SJ', + 'SK', + 'SKI', + 'SKIN', + 'SKY', + 'SKYPE', + 'SL', + 'SLING', + 'SM', + 'SMART', + 'SMILE', + 'SN', + 'SNCF', + 'SO', + 'SOCCER', + 'SOCIAL', + 'SOFTBANK', + 'SOFTWARE', + 'SOHU', + 'SOLAR', + 'SOLUTIONS', + 'SONG', + 'SONY', + 'SOY', + 'SPA', + 'SPACE', + 'SPORT', + 'SPOT', + 'SR', + 'SRL', + 'SS', + 'ST', + 'STADA', + 'STAPLES', + 'STAR', + 'STATEBANK', + 'STATEFARM', + 'STC', + 'STCGROUP', + 'STOCKHOLM', + 'STORAGE', + 'STORE', + 'STREAM', + 'STUDIO', + 'STUDY', + 'STYLE', + 'SU', + 'SUCKS', + 'SUPPLIES', + 'SUPPLY', + 'SUPPORT', + 'SURF', + 'SURGERY', + 'SUZUKI', + 'SV', + 'SWATCH', + 'SWISS', + 'SX', + 'SY', + 'SYDNEY', + 'SYSTEMS', + 'SZ', + 'TAB', + 'TAIPEI', + 'TALK', + 'TAOBAO', + 'TARGET', + 'TATAMOTORS', + 'TATAR', + 'TATTOO', + 'TAX', + 'TAXI', + 'TC', + 'TCI', + 'TD', + 'TDK', + 'TEAM', + 'TECH', + 'TECHNOLOGY', + 'TEL', + 'TEMASEK', + 'TENNIS', + 'TEVA', + 'TF', + 'TG', + 'TH', + 'THD', + 'THEATER', + 'THEATRE', + 'TIAA', + 'TICKETS', + 'TIENDA', + 'TIPS', + 'TIRES', + 'TIROL', + 'TJ', + 'TJMAXX', + 'TJX', + 'TK', + 'TKMAXX', + 'TL', + 'TM', + 'TMALL', + 'TN', + 'TO', + 'TODAY', + 'TOKYO', + 'TOOLS', + 'TOP', + 'TORAY', + 'TOSHIBA', + 'TOTAL', + 'TOURS', + 'TOWN', + 'TOYOTA', + 'TOYS', + 'TR', + 'TRADE', + 'TRADING', + 'TRAINING', + 'TRAVEL', + 'TRAVELERS', + 'TRAVELERSINSURANCE', + 'TRUST', + 'TRV', + 'TT', + 'TUBE', + 'TUI', + 'TUNES', + 'TUSHU', + 'TV', + 'TVS', + 'TW', + 'TZ', + 'UA', + 'UBANK', + 'UBS', + 'UG', + 'UK', + 'UNICOM', + 'UNIVERSITY', + 'UNO', + 'UOL', + 'UPS', + 'US', + 'UY', + 'UZ', + 'VA', + 'VACATIONS', + 'VANA', + 'VANGUARD', + 'VC', + 'VE', + 'VEGAS', + 'VENTURES', + 'VERISIGN', + 'VERSICHERUNG', + 'VET', + 'VG', + 'VI', + 'VIAJES', + 'VIDEO', + 'VIG', + 'VIKING', + 'VILLAS', + 'VIN', + 'VIP', + 'VIRGIN', + 'VISA', + 'VISION', + 'VIVA', + 'VIVO', + 'VLAANDEREN', + 'VN', + 'VODKA', + 'VOLVO', + 'VOTE', + 'VOTING', + 'VOTO', + 'VOYAGE', + 'VU', + 'WALES', + 'WALMART', + 'WALTER', + 'WANG', + 'WANGGOU', + 'WATCH', + 'WATCHES', + 'WEATHER', + 'WEATHERCHANNEL', + 'WEBCAM', + 'WEBER', + 'WEBSITE', + 'WED', + 'WEDDING', + 'WEIBO', + 'WEIR', + 'WF', + 'WHOSWHO', + 'WIEN', + 'WIKI', + 'WILLIAMHILL', + 'WIN', + 'WINDOWS', + 'WINE', + 'WINNERS', + 'WME', + 'WOLTERSKLUWER', + 'WOODSIDE', + 'WORK', + 'WORKS', + 'WORLD', + 'WOW', + 'WS', + 'WTC', + 'WTF', + 'XBOX', + 'XEROX', + 'XFINITY', + 'XIHUAN', + 'XIN', + 'XN--11B4C3D', + 'XN--1CK2E1B', + 'XN--1QQW23A', + 'XN--2SCRJ9C', + 'XN--30RR7Y', + 'XN--3BST00M', + 'XN--3DS443G', + 'XN--3E0B707E', + 'XN--3HCRJ9C', + 'XN--3PXU8K', + 'XN--42C2D9A', + 'XN--45BR5CYL', + 'XN--45BRJ9C', + 'XN--45Q11C', + 'XN--4DBRK0CE', + 'XN--4GBRIM', + 'XN--54B7FTA0CC', + 'XN--55QW42G', + 'XN--55QX5D', + 'XN--5SU34J936BGSG', + 'XN--5TZM5G', + 'XN--6FRZ82G', + 'XN--6QQ986B3XL', + 'XN--80ADXHKS', + 'XN--80AO21A', + 'XN--80AQECDR1A', + 'XN--80ASEHDB', + 'XN--80ASWG', + 'XN--8Y0A063A', + 'XN--90A3AC', + 'XN--90AE', + 'XN--90AIS', + 'XN--9DBQ2A', + 'XN--9ET52U', + 'XN--9KRT00A', + 'XN--B4W605FERD', + 'XN--BCK1B9A5DRE4C', + 'XN--C1AVG', + 'XN--C2BR7G', + 'XN--CCK2B3B', + 'XN--CCKWCXETD', + 'XN--CG4BKI', + 'XN--CLCHC0EA0B2G2A9GCD', + 'XN--CZR694B', + 'XN--CZRS0T', + 'XN--CZRU2D', + 'XN--D1ACJ3B', + 'XN--D1ALF', + 'XN--E1A4C', + 'XN--ECKVDTC9D', + 'XN--EFVY88H', + 'XN--FCT429K', + 'XN--FHBEI', + 'XN--FIQ228C5HS', + 'XN--FIQ64B', + 'XN--FIQS8S', + 'XN--FIQZ9S', + 'XN--FJQ720A', + 'XN--FLW351E', + 'XN--FPCRJ9C3D', + 'XN--FZC2C9E2C', + 'XN--FZYS8D69UVGM', + 'XN--G2XX48C', + 'XN--GCKR3F0F', + 'XN--GECRJ9C', + 'XN--GK3AT1E', + 'XN--H2BREG3EVE', + 'XN--H2BRJ9C', + 'XN--H2BRJ9C8C', + 'XN--HXT814E', + 'XN--I1B6B1A6A2E', + 'XN--IMR513N', + 'XN--IO0A7I', + 'XN--J1AEF', + 'XN--J1AMH', + 'XN--J6W193G', + 'XN--JLQ480N2RG', + 'XN--JVR189M', + 'XN--KCRX77D1X4A', + 'XN--KPRW13D', + 'XN--KPRY57D', + 'XN--KPUT3I', + 'XN--L1ACC', + 'XN--LGBBAT1AD8J', + 'XN--MGB9AWBF', + 'XN--MGBA3A3EJT', + 'XN--MGBA3A4F16A', + 'XN--MGBA7C0BBN0A', + 'XN--MGBAAM7A8H', + 'XN--MGBAB2BD', + 'XN--MGBAH1A3HJKRD', + 'XN--MGBAI9AZGQP6J', + 'XN--MGBAYH7GPA', + 'XN--MGBBH1A', + 'XN--MGBBH1A71E', + 'XN--MGBC0A9AZCG', + 'XN--MGBCA7DZDO', + 'XN--MGBCPQ6GPA1A', + 'XN--MGBERP4A5D4AR', + 'XN--MGBGU82A', + 'XN--MGBI4ECEXP', + 'XN--MGBPL2FH', + 'XN--MGBT3DHD', + 'XN--MGBTX2B', + 'XN--MGBX4CD0AB', + 'XN--MIX891F', + 'XN--MK1BU44C', + 'XN--MXTQ1M', + 'XN--NGBC5AZD', + 'XN--NGBE9E0A', + 'XN--NGBRX', + 'XN--NODE', + 'XN--NQV7F', + 'XN--NQV7FS00EMA', + 'XN--NYQY26A', + 'XN--O3CW4H', + 'XN--OGBPF8FL', + 'XN--OTU796D', + 'XN--P1ACF', + 'XN--P1AI', + 'XN--PGBS0DH', + 'XN--PSSY2U', + 'XN--Q7CE6A', + 'XN--Q9JYB4C', + 'XN--QCKA1PMC', + 'XN--QXA6A', + 'XN--QXAM', + 'XN--RHQV96G', + 'XN--ROVU88B', + 'XN--RVC1E0AM3E', + 'XN--S9BRJ9C', + 'XN--SES554G', + 'XN--T60B56A', + 'XN--TCKWE', + 'XN--TIQ49XQYJ', + 'XN--UNUP4Y', + 'XN--VERMGENSBERATER-CTB', + 'XN--VERMGENSBERATUNG-PWB', + 'XN--VHQUV', + 'XN--VUQ861B', + 'XN--W4R85EL8FHU5DNRA', + 'XN--W4RS40L', + 'XN--WGBH1C', + 'XN--WGBL6A', + 'XN--XHQ521B', + 'XN--XKC2AL3HYE2A', + 'XN--XKC2DL3A5EE0H', + 'XN--Y9A3AQ', + 'XN--YFRO4I67O', + 'XN--YGBI2AMMX', + 'XN--ZFR164B', + 'XXX', + 'XYZ', + 'YACHTS', + 'YAHOO', + 'YAMAXUN', + 'YANDEX', + 'YE', + 'YODOBASHI', + 'YOGA', + 'YOKOHAMA', + 'YOU', + 'YOUTUBE', + 'YT', + 'YUN', + 'ZA', + 'ZAPPOS', + 'ZARA', + 'ZERO', + 'ZIP', + 'ZM', + 'ZONE', + 'ZUERICH', + 'ZW' +]; - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - function FFTM (x, y) { - this.x = x; - this.y = y; - } +// Keep as upper-case to make updating from source easier - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } +module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase())); - return t; - }; - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; +/***/ }), - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } +/***/ 74983: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return rb; - }; +"use strict"; - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); +const Assert = __nccwpck_require__(32718); +const EscapeRegex = __nccwpck_require__(91965); - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); +const internals = {}; - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; +internals.generate = function () { - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; + const rfc3986 = {}; - var rx = rtwdf_ * ro - itwdf_ * io; + const hexDigit = '\\dA-Fa-f'; // HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" + const hexDigitOnly = '[' + hexDigit + ']'; - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; + const unreserved = '\\w-\\.~'; // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + const subDelims = '!\\$&\'\\(\\)\\*\\+,;='; // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + const pctEncoded = '%' + hexDigit; // pct-encoded = "%" HEXDIG HEXDIG + const pchar = unreserved + pctEncoded + subDelims + ':@'; // pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + const pcharOnly = '[' + pchar + ']'; + const decOctect = '(?:0{0,2}\\d|0?[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])'; // dec-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35 ; 0-9 / 10-99 / 100-199 / 200-249 / 250-255 - rtws[p + j] = re + ro; - itws[p + j] = ie + io; + rfc3986.ipv4address = '(?:' + decOctect + '\\.){3}' + decOctect; // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; + /* + h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal + ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address + IPv6address = 6( h16 ":" ) ls32 + / "::" 5( h16 ":" ) ls32 + / [ h16 ] "::" 4( h16 ":" ) ls32 + / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + / [ *4( h16 ":" ) h16 ] "::" ls32 + / [ *5( h16 ":" ) h16 ] "::" h16 + / [ *6( h16 ":" ) h16 ] "::" + */ - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; + const h16 = hexDigitOnly + '{1,4}'; + const ls32 = '(?:' + h16 + ':' + h16 + '|' + rfc3986.ipv4address + ')'; + const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32; + const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32; + const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32; + const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32; + const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32; + const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32; + const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32; + const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16; + const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::'; - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; + rfc3986.ipv4Cidr = '(?:\\d|[1-2]\\d|3[0-2])'; // IPv4 cidr = DIGIT / %x31-32 DIGIT / "3" %x30-32 ; 0-9 / 10-29 / 30-32 + rfc3986.ipv6Cidr = '(?:0{0,2}\\d|0?[1-9]\\d|1[01]\\d|12[0-8])'; // IPv6 cidr = DIGIT / %x31-39 DIGIT / "1" %x0-1 DIGIT / "12" %x0-8; 0-9 / 10-99 / 100-119 / 120-128 + rfc3986.ipv6address = '(?:' + IPv6SixHex + '|' + IPv6FiveHex + '|' + IPv6FourHex + '|' + IPv6ThreeHex + '|' + IPv6TwoHex + '|' + IPv6OneHex + '|' + IPv6NoneHex + '|' + IPv6NoneHex2 + '|' + IPv6NoneHex3 + ')'; + rfc3986.ipvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; // IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } + rfc3986.scheme = '[a-zA-Z][a-zA-Z\\d+-\\.]*'; // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + rfc3986.schemeRegex = new RegExp(rfc3986.scheme); - return 1 << i + 1 + odd; - }; + const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; // userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) + const IPLiteral = '\\[(?:' + rfc3986.ipv6address + '|' + rfc3986.ipvFuture + ')\\]'; // IP-literal = "[" ( IPv6address / IPvFuture ) "]" + const regName = '[' + unreserved + pctEncoded + subDelims + ']{1,255}'; // reg-name = *( unreserved / pct-encoded / sub-delims ) + const host = '(?:' + IPLiteral + '|' + rfc3986.ipv4address + '|' + regName + ')'; // host = IP-literal / IPv4address / reg-name + const port = '\\d*'; // port = *DIGIT + const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; // authority = [ userinfo "@" ] host [ ":" port ] + const authorityCapture = '(?:' + userinfo + '@)?(' + host + ')(?::' + port + ')?'; - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; + /* + segment = *pchar + segment-nz = 1*pchar + path = path-abempty ; begins with "/" '|' is empty + / path-absolute ; begins with "/" but not "//" + / path-noscheme ; begins with a non-colon segment + / path-rootless ; begins with a segment + / path-empty ; zero characters + path-abempty = *( "/" segment ) + path-absolute = "/" [ segment-nz *( "/" segment ) ] + path-rootless = segment-nz *( "/" segment ) + */ - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; + const segment = pcharOnly + '*'; + const segmentNz = pcharOnly + '+'; + const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+'; + const pathEmpty = ''; + const pathAbEmpty = '(?:\\/' + segment + ')*'; + const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?'; + const pathRootless = segmentNz + pathAbEmpty; + const pathNoScheme = segmentNzNc + pathAbEmpty; + const pathAbNoAuthority = '(?:\\/\\/\\/' + segment + pathAbEmpty + ')'; // Used by file:/// - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; + // hier-part = "//" authority path - t = iws[i]; + rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + '|' + pathAbNoAuthority + ')'; + rfc3986.hierPartCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathRootless + ')'; - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; + // relative-part = "//" authority path-abempty / path-absolute / path-noscheme / path-empty - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; + rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; + rfc3986.relativeRefCapture = '(?:' + '(?:\\/\\/' + authorityCapture + pathAbEmpty + ')' + '|' + pathAbsolute + '|' + pathNoScheme + '|' + pathEmpty + ')'; - ws[i] = w & 0x3ffffff; + // query = *( pchar / "/" / "?" ) + // query = *( pchar / "[" / "]" / "/" / "?" ) - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } + rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part '|' end of the line. + rfc3986.queryWithSquareBrackets = '[' + pchar + '\\[\\]\\/\\?]*(?=#|$)'; - return ws; - }; + // fragment = *( pchar / "/" / "?" ) - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); + rfc3986.fragment = '[' + pchar + '\\/\\?]*'; - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } + return rfc3986; +}; - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } +internals.rfc3986 = internals.generate(); - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } +exports.ip = { + v4Cidr: internals.rfc3986.ipv4Cidr, + v6Cidr: internals.rfc3986.ipv6Cidr, + ipv4: internals.rfc3986.ipv4address, + ipv6: internals.rfc3986.ipv6address, + ipvfuture: internals.rfc3986.ipvFuture +}; - return ph; - }; - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); +internals.createRegex = function (options) { - var rbt = this.makeRBT(N); + const rfc = internals.rfc3986; - var _ = this.stub(N); + // Construct expression - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); + const query = options.allowQuerySquareBrackets ? rfc.queryWithSquareBrackets : rfc.query; + const suffix = '(?:\\?' + query + ')?' + '(?:#' + rfc.fragment + ')?'; - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); + // relative-ref = relative-part [ "?" query ] [ "#" fragment ] - var rmws = out.words; - rmws.length = N; + const relative = options.domain ? rfc.relativeRefCapture : rfc.relativeRef; - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); + if (options.relativeOnly) { + return internals.wrap(relative + suffix); + } - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); + // Custom schemes - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } + let customScheme = ''; + if (options.scheme) { + Assert(options.scheme instanceof RegExp || typeof options.scheme === 'string' || Array.isArray(options.scheme), 'scheme must be a RegExp, String, or Array'); - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); + const schemes = [].concat(options.scheme); + Assert(schemes.length >= 1, 'scheme must have at least 1 scheme specified'); - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out._strip(); - }; + // Flatten the array into a string to be used to match the schemes - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; + const selections = []; + for (let i = 0; i < schemes.length; ++i) { + const scheme = schemes[i]; + Assert(scheme instanceof RegExp || typeof scheme === 'string', 'scheme at position ' + i + ' must be a RegExp or String'); - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; + if (scheme instanceof RegExp) { + selections.push(scheme.source.toString()); + } + else { + Assert(rfc.schemeRegex.test(scheme), 'scheme at position ' + i + ' must be a valid scheme'); + selections.push(EscapeRegex(scheme)); + } + } - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; + customScheme = selections.join('|'); + } - BN.prototype.imuln = function imuln (num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; + // URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] - assert(typeof num === 'number'); - assert(num < 0x4000000); + const scheme = customScheme ? '(?:' + customScheme + ')' : rfc.scheme; + const absolute = '(?:' + scheme + ':' + (options.domain ? rfc.hierPartCapture : rfc.hierPart) + ')'; + const prefix = options.allowRelative ? '(?:' + absolute + '|' + relative + ')' : absolute; + return internals.wrap(prefix + suffix, customScheme); +}; - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } +internals.wrap = function (raw, scheme) { - return isNegNum ? this.ineg() : this; - }; + raw = `(?=.)(?!https?\:/(?:$|[^/]))(?!https?\:///)(?!https?\:[^/])${raw}`; // Require at least one character and explicitly forbid 'http:/' or HTTP with empty domain - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; + return { + raw, + regex: new RegExp(`^${raw}$`), + scheme + }; +}; - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; +internals.uriRegex = internals.createRegex({}); - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } +exports.regex = function (options = {}) { - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; + if (options.scheme || + options.allowRelative || + options.relativeOnly || + options.allowQuerySquareBrackets || + options.domain) { - res = res.mul(q); - } + return internals.createRegex(options); } - return res; - }; + return internals.uriRegex; +}; - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - if (r !== 0) { - var carry = 0; +/***/ }), - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } +/***/ 34379: +/***/ ((__unused_webpack_module, exports) => { - if (carry) { - this.words[i] = carry; - this.length++; - } - } +"use strict"; - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - for (i = 0; i < s; i++) { - this.words[i] = 0; - } +const internals = { + operators: ['!', '^', '*', '/', '%', '+', '-', '<', '<=', '>', '>=', '==', '!=', '&&', '||', '??'], + operatorCharacters: ['!', '^', '*', '/', '%', '+', '-', '<', '=', '>', '&', '|', '?'], + operatorsOrder: [['^'], ['*', '/', '%'], ['+', '-'], ['<', '<=', '>', '>='], ['==', '!='], ['&&'], ['||', '??']], + operatorsPrefix: ['!', 'n'], - this.length += s; - } + literals: { + '"': '"', + '`': '`', + '\'': '\'', + '[': ']' + }, - return this._strip(); - }; + numberRx: /^(?:[0-9]*(\.[0-9]*)?){1}$/, + tokenRx: /^[\w\$\#\.\@\:\{\}]+$/, - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; + symbol: Symbol('formula'), + settings: Symbol('settings') +}; - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; +exports.Parser = class { - h -= s; - h = Math.max(0, h); + constructor(string, options = {}) { - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } + if (!options[internals.settings] && + options.constants) { - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } + for (const constant in options.constants) { + const value = options.constants[constant]; + if (value !== null && + !['boolean', 'number', 'string'].includes(typeof value)) { - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } + throw new Error(`Formula constant ${constant} contains invalid ${typeof value} value type`); + } + } + } - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } + this.settings = options[internals.settings] ? options : Object.assign({ [internals.settings]: true, constants: {}, functions: {} }, options); + this.single = null; - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; + this._parts = null; + this._parse(string); } - return this._strip(); - }; + _parse(string) { - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; + let parts = []; + let current = ''; + let parenthesis = 0; + let literal = false; - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; + const flush = (inner) => { - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; + if (parenthesis) { + throw new Error('Formula missing closing parenthesis'); + } - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; + const last = parts.length ? parts[parts.length - 1] : null; - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; + if (!literal && + !current && + !inner) { - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; + return; + } - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; + if (last && + last.type === 'reference' && + inner === ')') { // Function - // Check bit and return - var w = this.words[s]; + last.type = 'function'; + last.value = this._subFormula(current, last.value); + current = ''; + return; + } - return !!(w & q); - }; + if (inner === ')') { // Segment + const sub = new exports.Parser(current, this.settings); + parts.push({ type: 'segment', value: sub }); + } + else if (literal) { + if (literal === ']') { // Reference + parts.push({ type: 'reference', value: current }); + current = ''; + return; + } - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; + parts.push({ type: 'literal', value: current }); // Literal + } + else if (internals.operatorCharacters.includes(current)) { // Operator + if (last && + last.type === 'operator' && + internals.operators.includes(last.value + current)) { // 2 characters operator - assert(this.negative === 0, 'imaskn works only with positive numbers'); + last.value += current; + } + else { + parts.push({ type: 'operator', value: current }); + } + } + else if (current.match(internals.numberRx)) { // Number + parts.push({ type: 'constant', value: parseFloat(current) }); + } + else if (this.settings.constants[current] !== undefined) { // Constant + parts.push({ type: 'constant', value: this.settings.constants[current] }); + } + else { // Reference + if (!current.match(internals.tokenRx)) { + throw new Error(`Formula contains invalid token: ${current}`); + } - if (this.length <= s) { - return this; - } + parts.push({ type: 'reference', value: current }); + } - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); + current = ''; + }; - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } + for (const c of string) { + if (literal) { + if (c === literal) { + flush(); + literal = false; + } + else { + current += c; + } + } + else if (parenthesis) { + if (c === '(') { + current += c; + ++parenthesis; + } + else if (c === ')') { + --parenthesis; + if (!parenthesis) { + flush(c); + } + else { + current += c; + } + } + else { + current += c; + } + } + else if (c in internals.literals) { + literal = internals.literals[c]; + } + else if (c === '(') { + flush(); + ++parenthesis; + } + else if (internals.operatorCharacters.includes(c)) { + flush(); + current = c; + flush(); + } + else if (c !== ' ') { + current += c; + } + else { + flush(); + } + } - return this._strip(); - }; + flush(); - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + // Replace prefix - to internal negative operator - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); + parts = parts.map((part, i) => { - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) <= num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } + if (part.type !== 'operator' || + part.value !== '-' || + i && parts[i - 1].type !== 'operator') { - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } + return part; + } - // Add without checks - return this._iaddn(num); - }; + return { type: 'operator', value: 'n' }; + }); - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; + // Validate tokens order - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); + let operator = false; + for (const part of parts) { + if (part.type === 'operator') { + if (internals.operatorsPrefix.includes(part.value)) { + continue; + } - return this; - }; + if (!operator) { + throw new Error('Formula contains an operator in invalid position'); + } - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); + if (!internals.operators.includes(part.value)) { + throw new Error(`Formula contains an unknown operator ${part.value}`); + } + } + else if (operator) { + throw new Error('Formula missing expected operator'); + } - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } + operator = !operator; + } - this.words[0] -= num; + if (!operator) { + throw new Error('Formula contains invalid trailing operator'); + } - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } + // Identify single part - return this._strip(); - }; + if (parts.length === 1 && + ['reference', 'literal', 'constant'].includes(parts[0].type)) { - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; + this.single = { type: parts[0].type === 'reference' ? 'reference' : 'value', value: parts[0].value }; + } - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; + // Process parts - BN.prototype.iabs = function iabs () { - this.negative = 0; + this._parts = parts.map((part) => { - return this; - }; + // Operators - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + if (part.type === 'operator') { + return internals.operatorsPrefix.includes(part.value) ? part : part.value; + } - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; + // Literals, constants, segments - this._expand(len); + if (part.type !== 'reference') { + return part.value; + } - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } + // References - if (carry === 0) return this._strip(); + if (this.settings.tokenRx && + !this.settings.tokenRx.test(part.value)) { - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; + throw new Error(`Formula contains invalid reference ${part.value}`); + } + + if (this.settings.reference) { + return this.settings.reference(part.value); + } + + return internals.reference(part.value); + }); } - this.negative = 1; - return this._strip(); - }; + _subFormula(string, name) { - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; + const method = this.settings.functions[name]; + if (typeof method !== 'function') { + throw new Error(`Formula contains unknown function ${name}`); + } - var a = this.clone(); - var b = num; + let args = []; + if (string) { + let current = ''; + let parenthesis = 0; + let literal = false; - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } + const flush = () => { - // Initialize quotient - var m = a.length - b.length; - var q; + if (!current) { + throw new Error(`Formula contains function ${name} with invalid arguments ${string}`); + } - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } + args.push(current); + current = ''; + }; - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } + for (let i = 0; i < string.length; ++i) { + const c = string[i]; + if (literal) { + current += c; + if (c === literal) { + literal = false; + } + } + else if (c in internals.literals && + !parenthesis) { - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); + current += c; + literal = internals.literals[c]; + } + else if (c === ',' && + !parenthesis) { - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); + flush(); + } + else { + current += c; + if (c === '(') { + ++parenthesis; + } + else if (c === ')') { + --parenthesis; + } + } + } - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; + flush(); } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q._strip(); - } - a._strip(); - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } + args = args.map((arg) => new exports.Parser(arg, this.settings)); - return { - div: q || null, - mod: a - }; - }; + return function (context) { - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); + const innerValues = []; + for (const arg of args) { + innerValues.push(arg.evaluate(context)); + } - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; + return method.call(context, ...innerValues); + }; } - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); + evaluate(context) { - if (mode !== 'mod') { - div = res.div.neg(); - } + const parts = this._parts.slice(); - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } + // Prefix operators - return { - div: div, - mod: mod - }; - } + for (let i = parts.length - 2; i >= 0; --i) { + const part = parts[i]; + if (part && + part.type === 'operator') { - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); + const current = parts[i + 1]; + parts.splice(i + 1, 1); + const value = internals.evaluate(current, context); + parts[i] = internals.single(part.value, value); + } + } - if (mode !== 'mod') { - div = res.div.neg(); - } + // Left-right operators - return { - div: div, - mod: res.mod - }; - } + internals.operatorsOrder.forEach((set) => { - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + for (let i = 1; i < parts.length - 1;) { + if (set.includes(parts[i])) { + const operator = parts[i]; + const left = internals.evaluate(parts[i - 1], context); + const right = internals.evaluate(parts[i + 1], context); - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + parts.splice(i, 2); + const result = internals.calculate(operator, left, right); + parts[i - 1] = result === 0 ? 0 : result; // Convert -0 + } + else { + i += 2; + } + } + }); - return { - div: res.div, - mod: mod - }; + return internals.evaluate(parts[0], context); } +}; - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } +exports.Parser.prototype[internals.symbol] = true; - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modrn(num.words[0])) - }; - } - return { - div: this.divn(num.words[0]), - mod: new BN(this.modrn(num.words[0])) - }; - } +internals.reference = function (name) { - return this._wordDiv(num, mode); - }; + return function (context) { - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; + return context && context[name] !== undefined ? context[name] : null; + }; +}; - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; +internals.evaluate = function (part, context) { - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); + if (part === null) { + return null; + } - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; + if (typeof part === 'function') { + return part(context); + } - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + if (part[internals.symbol]) { + return part.evaluate(context); + } - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); + return part; +}; - // Round down - if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; +internals.single = function (operator, value) { - BN.prototype.modrn = function modrn (num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; + if (operator === '!') { + return value ? false : true; + } - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; + // operator === 'n' - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; + const negative = -value; + if (negative === 0) { // Override -0 + return 0; } - return isNegNum ? -acc : acc; - }; + return negative; +}; - // WARNING: DEPRECATED - BN.prototype.modn = function modn (num) { - return this.modrn(num); - }; - // In-place division by number - BN.prototype.idivn = function idivn (num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; +internals.calculate = function (operator, left, right) { - assert(num <= 0x3ffffff); + if (operator === '??') { + return internals.exists(left) ? left : right; + } - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; + if (typeof left === 'string' || + typeof right === 'string') { + + if (operator === '+') { + left = internals.exists(left) ? left : ''; + right = internals.exists(right) ? right : ''; + return left + right; + } + } + else { + switch (operator) { + case '^': return Math.pow(left, right); + case '*': return left * right; + case '/': return left / right; + case '%': return left % right; + case '+': return left + right; + case '-': return left - right; + } } - this._strip(); - return isNegNum ? this.ineg() : this; - }; + switch (operator) { + case '<': return left < right; + case '<=': return left <= right; + case '>': return left > right; + case '>=': return left >= right; + case '==': return left === right; + case '!=': return left !== right; + case '&&': return left && right; + case '||': return left || right; + } - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; + return null; +}; - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - var x = this; - var y = p.clone(); +internals.exists = function (value) { - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } + return value !== null && value !== undefined; +}; - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); +/***/ }), - var g = 0; +/***/ 75604: +/***/ ((__unused_webpack_module, exports) => { - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } +"use strict"; - var yp = y.clone(); - var xp = x.clone(); - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } +const internals = {}; - A.iushrn(1); - B.iushrn(1); - } - } - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } +exports.location = function (depth = 0) { - C.iushrn(1); - D.iushrn(1); - } - } + const orig = Error.prepareStackTrace; + Error.prepareStackTrace = (ignore, stack) => stack; - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } + const capture = {}; + Error.captureStackTrace(capture, this); + const line = capture.stack[depth + 1]; + + Error.prepareStackTrace = orig; return { - a: C, - b: D, - gcd: y.iushln(g) + filename: line.getFileName(), + line: line.getLineNumber() }; - }; +}; - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - var a = this; - var b = p.clone(); +/***/ }), - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } +/***/ 83682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var x1 = new BN(1); - var x2 = new BN(0); +var register = __nccwpck_require__(44670); +var addHook = __nccwpck_require__(5549); +var removeHook = __nccwpck_require__(6819); - var delta = b.clone(); +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); +} - x1.iushrn(1); - } - } +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } +function HookCollection() { + var state = { + registry: {}, + }; - x2.iushrn(1); - } - } + var hook = register.bind(null, state); + bindApi(hook, state); - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } + return hook; +} - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; + } + return HookCollection(); +} - if (res.cmpn(0) < 0) { - res.iadd(p); - } +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); - return res; - }; +module.exports = Hook; +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; +/***/ }), - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } +/***/ 5549: +/***/ ((module) => { - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } +module.exports = addHook; - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } - a.isub(b); - } while (true); + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } - return b.iushln(shift); - }; + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; + } - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; +/***/ }), - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; +/***/ 44670: +/***/ ((module) => { - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } +module.exports = register; - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; + if (!options) { + options = {}; + } - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); + } - this._strip(); + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - assert(num <= 0x3ffffff, 'Number is too big'); +/***/ }), - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; +/***/ 6819: +/***/ ((module) => { - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; +module.exports = removeHook; - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; + if (index === -1) { + return; + } - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; + state.registry[name].splice(index, 1); +} - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; +/***/ }), - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; +/***/ 6641: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; +/* module decorator */ module = __nccwpck_require__.nmd(module); +(function (module, exports) { + 'use strict'; - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; + // BN - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; + this.negative = 0; + this.words = null; + this.length = 0; - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; + // Reduction context + this.red = null; - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; + BN.BN = BN; + BN.wordSize = 26; - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__nccwpck_require__(14300).Buffer); + } + } catch (e) { + } - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; }; - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; }; - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } }; - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [number & 0x3ffffff]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; + if (endian !== 'le') return; - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); + // Reverse the bytes + this._initArray(this.toArray(), base, endian); }; - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this._strip(); }; - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // '0' - '9' + if (c >= 48 && c <= 57) { + return c - 48; + // 'A' - 'F' + } else if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert(false, 'Invalid character in ' + string); + } } - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + // 24-bits chunks + var off = 0; + var j = 0; - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } } else { - if (r.strip !== undefined) { - // r is a BN v4 instance - r.strip(); - } else { - // r is a BN v5 instance - r._strip(); + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } } } - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); + this._strip(); }; - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; + function parseBase (str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); + r *= mul; - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; + // 'a' + if (c >= 49) { + b = c - 49 + 0xa; - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; + // 'A' + } else if (c >= 17) { + b = c - 17 + 0xa; - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; + // '0' - '9' + } else { + b = c; + } + assert(c >= 0 && b < mul, 'Invalid character'); + r += b; } + return r; + } - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [0]; + this.length = 1; - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; } - }; + limbLen--; + limbPow = (limbPow / base) | 0; - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } } - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); } } - return num; + + this._strip(); }; - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + function move (dest, src) { + dest.words = src.words; + dest.length = src.length; + dest.negative = src.negative; + dest.red = src.red; } - inherits(P192, MPrime); - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); + BN.prototype._move = function _move (dest) { + move(dest, this); + }; - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; } - return num; + return this; }; - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); + // Remove leading `0` from `this` + BN.prototype._strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; } - primes[name] = prime; + return this._normSign(); + }; - return prime; + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; }; - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; + // Check Symbol.for because not everywhere where Symbol defined + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility + if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { + try { + BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; + } catch (e) { + BN.prototype.inspect = inspect; } + } else { + BN.prototype.inspect = inspect; } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; + function inspect () { + return (this.red ? ''; + } - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); + /* - move(a, a.umod(this.m)._forceRed(this)); - return a; - }; + var zeros = []; + var groupSizes = []; + var groupBases = []; - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } - return this.m.sub(a)._forceRed(this); - }; + */ - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; } - return res; - }; - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modrn(groupBase).toString(base); + c = c.idivn(groupBase); - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; } - return res._forceRed(this); - }; - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); + assert(false, 'Base should be between 2 and 36'); + }; - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); } - return res; + return (this.negative !== 0) ? -ret : ret; }; - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); + BN.prototype.toJSON = function toJSON () { + return this.toString(16, 2); }; - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; + if (Buffer) { + BN.prototype.toBuffer = function toBuffer (endian, length) { + return this.toArrayLike(Buffer, endian, length); + }; + } - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); }; - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); + var allocate = function allocate (ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); + } + return new ArrayType(size); }; - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + this._strip(); + + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + var res = allocate(ArrayType, reqLength); + var postfix = endian === 'le' ? 'LE' : 'BE'; + this['_toArrayLike' + postfix](res, byteLength); + return res; }; - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { + var position = 0; + var carry = 0; - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); + res[position++] = word & 0xff; + if (position < res.length) { + res[position++] = (word >> 8) & 0xff; + } + if (position < res.length) { + res[position++] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position < res.length) { + res[position++] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } } - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); + if (position < res.length) { + res[position++] = carry; + + while (position < res.length) { + res[position++] = 0; + } } - assert(!q.isZero()); + }; - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); + BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { + var position = res.length - 1; + var carry = 0; - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); + res[position--] = word & 0xff; + if (position >= 0) { + res[position--] = (word >> 8) & 0xff; + } + if (position >= 0) { + res[position--] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position >= 0) { + res[position--] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } } - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); + if (position >= 0) { + res[position--] = carry; + + while (position >= 0) { + res[position--] = 0; } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); + } + }; - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; } - return r; }; - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; }; - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); + function toBitArray (num) { + var w = new Array(num.bitLength()); - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; + w[bit] = (num.words[off] >>> wbit) & 0x01; } - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } + return w; + } - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; } + return r; + }; - return res; + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); }; - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - return r === num ? r.clone() : r; + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); }; - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; }; - // - // Montgomery method engine - // + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; - BN.mont = function mont (num) { - return new Mont(num); + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; }; - function Mont (m) { - Red.call(this, m); + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; } - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); + return this._strip(); + }; - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); }; - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); }; - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; } - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; } - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } + this.length = b.length; - return res._forceRed(this); + return this._strip(); }; - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); }; -})( false || module, this); + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; -/***/ }), - -/***/ 96425: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getCondense = __nccwpck_require__(15631); + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } -/* build/tpl */ + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } -function addCondense(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('condense', getCondense(), !getCondense.notChainable); -} + this.length = a.length; -module.exports = addCondense; + return this._strip(); + }; + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; -/***/ }), + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; -/***/ 25591: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; -"use strict"; + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getCondenseDeep = __nccwpck_require__(6198); + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); -/* build/tpl */ + if (bitsLeft > 0) { + bytesNeeded--; + } -function addCondenseDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('condenseDeep', getCondenseDeep(_), !getCondenseDeep.notChainable); -} + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } -module.exports = addCondenseDeep; + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + // And remove leading zeroes + return this._strip(); + }; -/***/ }), + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; -/***/ 39683: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); -"use strict"; + var off = (bit / 26) | 0; + var wbit = bit % 26; + this._expand(off + 1); -var getMixOrPatchIn = __nccwpck_require__(22514); -var getEachDeep = __nccwpck_require__(47016); + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } -/* build/tpl */ + return this._strip(); + }; -function addEachDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('eachDeep', getEachDeep(_), !getEachDeep.notChainable); -} + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; -module.exports = addEachDeep; + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } -/***/ }), + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } -/***/ 88701: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } -"use strict"; + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getExists = __nccwpck_require__(84282); + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } -/* build/tpl */ + if (this.length > num.length) return this.clone().iadd(num); -function addExists(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('exists', getExists(_), !getExists.notChainable); -} + return num.clone().iadd(this); + }; -module.exports = addExists; + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } -/***/ }), + // At this point both numbers are positive + var cmp = this.cmp(num); -/***/ 91422: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } -"use strict"; + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getFilterDeep = __nccwpck_require__(79175); + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } -/* build/tpl */ + this.length = Math.max(this.length, i); -function addFilterDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('filterDeep', getFilterDeep(_), !getFilterDeep.notChainable); -} + if (a !== this) { + this.negative = 1; + } -module.exports = addFilterDeep; + return this._strip(); + }; + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; -/***/ }), + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; -/***/ 73592: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; -"use strict"; + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getFindDeep = __nccwpck_require__(14850); + return out._strip(); + } -/* build/tpl */ + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; -function addFindDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('findDeep', getFindDeep(_), !getFindDeep.notChainable); -} + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; -module.exports = addFindDeep; + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; -/***/ }), + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; -/***/ 41368: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; -"use strict"; + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out._strip(); + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getFindPathDeep = __nccwpck_require__(73970); + function jumboMulTo (self, num, out) { + // Temporary disable, see https://github.com/indutny/bn.js/issues/211 + // var fftm = new FFTM(); + // return fftm.mulp(self, num, out); + return bigMulTo(self, num, out); + } -/* build/tpl */ + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } -function addFindPathDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('findPathDeep', getFindPathDeep(_), !getFindPathDeep.notChainable); -} + return res; + }; -module.exports = addFindPathDeep; + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + function FFTM (x, y) { + this.x = x; + this.y = y; + } -/***/ }), + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } -/***/ 97447: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return t; + }; -"use strict"; + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getFindValueDeep = __nccwpck_require__(84392); + return rb; + }; -/* build/tpl */ + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; -function addFindValueDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('findValueDeep', getFindValueDeep(_), !getFindValueDeep.notChainable); -} + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); -module.exports = addFindValueDeep; + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); -/***/ }), + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; -/***/ 31114: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; -"use strict"; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + var rx = rtwdf_ * ro - itwdf_ * io; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getForEachDeep = __nccwpck_require__(47164); + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; -/* build/tpl */ + rtws[p + j] = re + ro; + itws[p + j] = ie + io; -function addForEachDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('forEachDeep', getForEachDeep(_), !getForEachDeep.notChainable); -} + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; -module.exports = addForEachDeep; + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; -/***/ }), + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } -/***/ 99634: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return 1 << i + 1 + odd; + }; -"use strict"; + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getIndex = __nccwpck_require__(13953); + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; -/* build/tpl */ + t = iws[i]; -function addIndex(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('index', getIndex(_), !getIndex.notChainable); -} + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; -module.exports = addIndex; + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + ws[i] = w & 0x3ffffff; -/***/ }), + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } -/***/ 82400: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return ws; + }; -"use strict"; + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getKeysDeep = __nccwpck_require__(91152); + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } -/* build/tpl */ + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; -function addKeysDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('keysDeep', getKeysDeep(_), !getKeysDeep.notChainable); -} + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } -module.exports = addKeysDeep; + return ph; + }; + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); -/***/ }), + var rbt = this.makeRBT(N); -/***/ 30547: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var _ = this.stub(N); -"use strict"; + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); -var getMixOrPatchIn = __nccwpck_require__(22514); -var getMapDeep = __nccwpck_require__(86139); + var rmws = out.words; + rmws.length = N; -/* build/tpl */ + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); -function addMapDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('mapDeep', getMapDeep(_), !getMapDeep.notChainable); -} + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); -module.exports = addMapDeep; + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); -/***/ }), + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out._strip(); + }; -/***/ 51391: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; -"use strict"; + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getMapKeysDeep = __nccwpck_require__(28192); + BN.prototype.imuln = function imuln (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; -/* build/tpl */ + assert(typeof num === 'number'); + assert(num < 0x4000000); -function addMapKeysDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('mapKeysDeep', getMapKeysDeep(_), !getMapKeysDeep.notChainable); -} + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } -module.exports = addMapKeysDeep; + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return isNegNum ? this.ineg() : this; + }; -/***/ }), + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; -/***/ 13354: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; -"use strict"; + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); -var getMixOrPatchIn = __nccwpck_require__(22514); -var getMapValuesDeep = __nccwpck_require__(49743); + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } -/* build/tpl */ + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; -function addMapValuesDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('mapValuesDeep', getMapValuesDeep(_), !getMapValuesDeep.notChainable); -} + res = res.mul(q); + } + } -module.exports = addMapValuesDeep; + return res; + }; + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; -/***/ }), + if (r !== 0) { + var carry = 0; -/***/ 86835: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } -"use strict"; + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getOmitDeep = __nccwpck_require__(81192); + for (i = 0; i < s; i++) { + this.words[i] = 0; + } -/* build/tpl */ + this.length += s; + } -function addOmitDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('omitDeep', getOmitDeep(_), !getOmitDeep.notChainable); -} + return this._strip(); + }; -module.exports = addOmitDeep; + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } -/***/ }), + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; -/***/ 41612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + h -= s; + h = Math.max(0, h); -"use strict"; + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getPathMatches = __nccwpck_require__(8127); + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } -/* build/tpl */ + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } -function addPathMatches(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('pathMatches', getPathMatches(_), !getPathMatches.notChainable); -} + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } -module.exports = addPathMatches; + return this._strip(); + }; + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; -/***/ }), + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; -/***/ 18017: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; -"use strict"; + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getPathToString = __nccwpck_require__(69937); + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; -/* build/tpl */ + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; -function addPathToString(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('pathToString', getPathToString(_), !getPathToString.notChainable); -} + // Check bit and return + var w = this.words[s]; -module.exports = addPathToString; + return !!(w & q); + }; + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; -/***/ }), + assert(this.negative === 0, 'imaskn works only with positive numbers'); -/***/ 84397: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.length <= s) { + return this; + } -"use strict"; + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } -var getMixOrPatchIn = __nccwpck_require__(22514); -var getPaths = __nccwpck_require__(49633); + return this._strip(); + }; -/* build/tpl */ + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; -function addPaths(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('paths', getPaths(_), !getPaths.notChainable); -} + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); -module.exports = addPaths; + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } -/***/ }), + // Add without checks + return this._iaddn(num); + }; -/***/ 83080: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; -"use strict"; + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getPickDeep = __nccwpck_require__(64541); + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); -/* build/tpl */ + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } -function addPickDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('pickDeep', getPickDeep(_), !getPickDeep.notChainable); -} + this.words[0] -= num; -module.exports = addPickDeep; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + return this._strip(); + }; -/***/ }), + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; -/***/ 1643: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; -"use strict"; + BN.prototype.iabs = function iabs () { + this.negative = 0; + return this; + }; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getReduceDeep = __nccwpck_require__(97878); + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; -/* build/tpl */ + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; -function addReduceDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('reduceDeep', getReduceDeep(_), !getReduceDeep.notChainable); -} + this._expand(len); -module.exports = addReduceDeep; + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + if (carry === 0) return this._strip(); -/***/ }), + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; -/***/ 55221: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this._strip(); + }; -"use strict"; + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; -var getMixOrPatchIn = __nccwpck_require__(22514); -var getSomeDeep = __nccwpck_require__(34949); + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } -/* build/tpl */ + // Initialize quotient + var m = a.length - b.length; + var q; -function addSomeDeep(_) { - var mixOrPatchIn = getMixOrPatchIn(_); - return mixOrPatchIn('someDeep', getSomeDeep(_), !getSomeDeep.notChainable); -} + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } -module.exports = addSomeDeep; + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); -/***/ }), + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); -/***/ 13503: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q._strip(); + } + a._strip(); -"use strict"; + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; -var addCondense = __nccwpck_require__(96425); -var addCondenseDeep = __nccwpck_require__(25591); -var addEachDeep = __nccwpck_require__(39683); -var addExists = __nccwpck_require__(88701); -var addFilterDeep = __nccwpck_require__(91422); -var addFindDeep = __nccwpck_require__(73592); -var addFindPathDeep = __nccwpck_require__(41368); -var addFindValueDeep = __nccwpck_require__(97447); -var addForEachDeep = __nccwpck_require__(31114); -var addIndex = __nccwpck_require__(99634); -var addKeysDeep = __nccwpck_require__(82400); -var addMapDeep = __nccwpck_require__(30547); -var addMapKeysDeep = __nccwpck_require__(51391); -var addMapValuesDeep = __nccwpck_require__(13354); -var addOmitDeep = __nccwpck_require__(86835); -var addPathMatches = __nccwpck_require__(41612); -var addPathToString = __nccwpck_require__(18017); -var addPaths = __nccwpck_require__(84397); -var addPickDeep = __nccwpck_require__(83080); -var addReduceDeep = __nccwpck_require__(1643); -var addSomeDeep = __nccwpck_require__(55221); + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); -/* build/tpl */ + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } -function apply(_) { - addCondense(_); - addCondenseDeep(_); - addEachDeep(_); - addExists(_); - addFilterDeep(_); - addFindDeep(_); - addFindPathDeep(_); - addFindValueDeep(_); - addForEachDeep(_); - addIndex(_); - addKeysDeep(_); - addMapDeep(_); - addMapKeysDeep(_); - addMapValuesDeep(_); - addOmitDeep(_); - addPathMatches(_); - addPathToString(_); - addPaths(_); - addPickDeep(_); - addReduceDeep(_); - addSomeDeep(_); + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); - return _; -} + if (mode !== 'mod') { + div = res.div.neg(); + } -module.exports = apply; + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div: div, + mod: mod + }; + } -/***/ }), + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); -/***/ 15631: -/***/ ((module) => { + if (mode !== 'mod') { + div = res.div.neg(); + } -"use strict"; + return { + div: div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); -function getCondense(_) { - function condense(arr) { - var indexes = []; - for (var i = 0; i < arr.length; i++) { - if (!(i in arr)) { - indexes.push(i); + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } } - } - var length = indexes.length; - while (length--) { - arr.splice(indexes[length], 1); + return { + div: res.div, + mod: mod + }; } - return arr; - } - return condense; -} -module.exports = getCondense; + // Both numbers are positive at this point + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } -/***/ }), + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } -/***/ 6198: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modrn(num.words[0])) + }; + } -"use strict"; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modrn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; -var getCondense = __nccwpck_require__(15631); -var getEachDeep = __nccwpck_require__(47016); + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; -function getCondenseDeep(_) { - var eachDeep = getEachDeep(_); - var condense = getCondense(); - var _each = _.each || _.forArray; - function condenseDeep(obj, options) { - options = _.merge( - { - checkCircular: false, - }, - options || {} - ); - var eachDeepOptions = { - checkCircular: options.checkCircular, - ownPropertiesOnly: options.ownPropertiesOnly, - }; - var arrays = []; - //console.log('condenseDeep → eachDeep'); - eachDeep( - obj, - function (value, key, parent, context) { - if (!context.isCircular && Array.isArray(value)) { arrays.push(value); } - }, - eachDeepOptions - ); - if (Array.isArray(obj)) { arrays.push(obj); } - _each(arrays, condense); - return obj; - } - return condenseDeep; -} + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; -module.exports = getCondenseDeep; + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; -/***/ }), + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; -/***/ 47016: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); -"use strict"; + // Round down + if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; -var getIterate = __nccwpck_require__(55267); + BN.prototype.modrn = function modrn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; -function getEachDeep(_) { - var iterate = getIterate(_); + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; - function eachDeep(obj, callback, options) { - if (callback === undefined) { callback = _.identity; } - options = _.merge( - { - includeRoot: !Array.isArray(obj), - pathFormat: 'string', - checkCircular: false, - leavesOnly: false, - ownPropertiesOnly: true, // - }, - options || {} - ); - if (options.childrenPath !== undefined) { - if (!options.includeRoot && options.rootIsChildren === undefined) { - options.rootIsChildren = Array.isArray(obj); - } - if ( - !_.isString(options.childrenPath) && - !Array.isArray(options.childrenPath) - ) { - throw Error('childrenPath can be string or array'); - } else { - if (_.isString(options.childrenPath)) { - options.childrenPath = [options.childrenPath]; - } - options.strChildrenPath = options.childrenPath; - options.childrenPath = []; - for (var i = options.strChildrenPath.length - 1; i >= 0; i--) { - options.childrenPath[i] = _.toPath(options.strChildrenPath[i]); - } - } + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; } - iterate({ - value: obj, - callback: callback, - options: options, - obj: obj, - }); - return obj; - } - return eachDeep; -} -module.exports = getEachDeep; + return isNegNum ? -acc : acc; + }; + // WARNING: DEPRECATED + BN.prototype.modn = function modn (num) { + return this.modrn(num); + }; -/***/ }), + // In-place division by number + BN.prototype.idivn = function idivn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; -/***/ 84282: -/***/ ((module) => { + assert(num <= 0x3ffffff); -"use strict"; + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + this._strip(); + return isNegNum ? this.ineg() : this; + }; -function getExists(_) { - function exists(obj, path) { - path = Array.isArray(path) ? _.clone(path) : _.toPath(path); - var key = path.pop(); - var parent = path.length ? _.get(obj, path) : obj; - return parent !== undefined && key in parent; - } - return exists; -} + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; -getExists.notChainable = true; + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); -module.exports = getExists; + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } -/***/ }), + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); -/***/ 79175: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); -"use strict"; + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } -var getCondense = __nccwpck_require__(15631); -var isObject = __nccwpck_require__(86564); -var getEachDeep = __nccwpck_require__(47016); + var yp = y.clone(); + var xp = x.clone(); -function getFilterDeep(_) { - var eachDeep = getEachDeep(_); - var condense = getCondense(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } - function filterDeep(obj, predicate, options) { - predicate = _.iteratee(predicate); - if (!options) { - options = {}; - } else { - options = _.cloneDeep(options); - if (options.leafsOnly !== undefined) { - options.leavesOnly = options.leafsOnly; - } - } - if (!options.onTrue) { - options.onTrue = {}; - } - if (!options.onFalse) { - options.onFalse = {}; - } - if (!options.onUndefined) { - options.onUndefined = {}; - } - if (options.childrenPath !== undefined) { - if (options.onTrue.skipChildren === undefined) { - options.onTrue.skipChildren = false; - } - if (options.onUndefined.skipChildren === undefined) { - options.onUndefined.skipChildren = false; - } - if (options.onFalse.skipChildren === undefined) { - options.onFalse.skipChildren = false; + A.iushrn(1); + B.iushrn(1); + } } - if (options.onTrue.cloneDeep === undefined) { - options.onTrue.cloneDeep = true; - } - if (options.onUndefined.cloneDeep === undefined) { - options.onUndefined.cloneDeep = true; + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } } - if (options.onFalse.cloneDeep === undefined) { - options.onFalse.cloneDeep = true; + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); } } - options = _.merge( - { - checkCircular: false, - keepCircular: true, - //replaceCircularBy: , - leavesOnly: options.childrenPath === undefined, - condense: true, - cloneDeep: _.cloneDeep, - pathFormat: 'string', - onTrue: { skipChildren: true, cloneDeep: true, keepIfEmpty: true }, - onUndefined: { - skipChildren: false, - cloneDeep: false, - keepIfEmpty: false, - }, - onFalse: { - skipChildren: true, - cloneDeep: false, - keepIfEmpty: false, - }, - }, - options - ); - var eachDeepOptions = { - pathFormat: options.pathFormat, - checkCircular: options.checkCircular, - childrenPath: options.childrenPath, - includeRoot: options.includeRoot, - rootIsChildren: options.rootIsChildren, - ownPropertiesOnly: options.ownPropertiesOnly, - callbackAfterIterate: true, - leavesOnly: false, + return { + a: C, + b: D, + gcd: y.iushln(g) }; - var resIsArray = Array.isArray(obj); - var res = resIsArray ? [] : isObject(obj) ? {} : null; - var toCondense = options.condense ? [] : false; - eachDeep( - obj, - function (value, key, parent, context) { - if (!context.afterIterate) { - context.info._filterDeep = {}; - if (!context.isCircular) { - var reply = - !options.leavesOnly || context.isLeaf - ? predicate(value, key, parent, context) - : undefined; + }; - if (!isObject(reply)) { - if (reply === undefined) { - reply = options.onUndefined; - } else if (reply) { - reply = options.onTrue; - } else { - reply = options.onFalse; - } - } - context.info._filterDeep.reply = reply; - context.info._filterDeep.empty = - reply.empty === undefined ? true : reply.empty; + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); - if (reply.keepIfEmpty || !reply.skipChildren) { - if (options.cloneDeep && reply.cloneDeep) { - if (context.path !== undefined) { - var children = takeResultParent(context, res); - context.info._filterDeep.res = children[ - key - ] = options.cloneDeep(value); - } else { - context.info._filterDeep.res = res = options.cloneDeep(value); - } - } else { - if (context.path !== undefined) { - var children$1 = takeResultParent(context, res); - context.info._filterDeep.res = children$1[key] = context.info - .isArray - ? [] - : context.info.isObject - ? {} - : value; - } else { - context.info._filterDeep.res = res = context.info.isArray - ? [] - : context.info.isObject - ? {} - : value; - } - } - } - return !reply.skipChildren; - } else { - var children$2 = takeResultParent(context, res); - if (!options.keepCircular) { - delete children$2[key]; - if ( - toCondense && - ((children$2 === context.parent.info._filterDeep.res && - context.parent.info.isArray) || - Array.isArray(children$2)) && - !context.parent.info._filterDeep.isSparse - ) { - context.parent.info._filterDeep.isSparse = true; - toCondense.push(context.parent.info); - } + var a = this; + var b = p.clone(); - context.info._filterDeep.excluded = true; - } else { - context.info._filterDeep.res = children$2[key] = - 'replaceCircularBy' in options - ? options.replaceCircularBy - : context.circularParent.path !== undefined - ? context.circularParent.info._filterDeep.res - : res; - } - return false; - } - } else if (context.afterIterate && !context.isCircular) { - var reply$1 = context.info._filterDeep.reply; + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } - if (context.info._filterDeep.empty && !reply$1.keepIfEmpty) { - if (context.path === undefined) { - res = null; - } else { - var children$3 = takeResultParent(context, res); - delete children$3[key]; - if ( - toCondense && - ((children$3 === context.parent.info._filterDeep.res && - context.parent.info.isArray) || - Array.isArray(children$3)) && - !context.parent.info._filterDeep.isSparse - ) { - context.parent.info._filterDeep.isSparse = true; - toCondense.push(context.parent.info); - } - context.info._filterDeep.excluded = true; - } - } else { - var parent$1 = context.parent; - while (parent$1) { - // if (!parent.info._filterDeep) { - // parent.info._filterDeep = {}; - // } - if (!parent$1.info._filterDeep.reply) { - parent$1.info._filterDeep.reply = options.onUndefined; - } - if (!parent$1.info._filterDeep.empty) { - break; - } - parent$1.info._filterDeep.empty = false; - parent$1 = parent$1.parent; - } + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); } - return; + x1.iushrn(1); } - }, - eachDeepOptions - ); + } - if (toCondense) { - for (var i = 0; i < toCondense.length; i++) { - var info = toCondense[i]; - if (info._filterDeep.isSparse && !info._filterDeep.excluded) { - condense(info.children); + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); } } - if (resIsArray) { - condense(res); + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); } } - if (resIsArray && !res.length && !eachDeepOptions.includeRoot) { - return null; + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); } return res; - } - return filterDeep; + }; - function takeResultParent(context, res) { - if (context.parent.info.children) { - return context.parent.info.children; - } - if (!context.parent.info._filterDeep) { - context.parent.info._filterDeep = {}; - } - var parent = context.parent.info._filterDeep.res; - if (parent === undefined) { - //if (!context.parent.parent) { - parent = context.parent.info._filterDeep.res = res; - // } else { - // parent = context.parent.info._filterDeep.res = Array.isArray(context.parent.value) - // ? [] - // : {}; - // } + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); } - if (context._item.childrenPath) { - var oParent = context.parent.value; - for (var i = 0; i < context._item.childrenPath.length; i++) { - var childKey = context._item.childrenPath[i]; - oParent = oParent[childKey]; - if (!parent[childKey]) { - parent[childKey] = Array.isArray(oParent) ? [] : {}; - } - parent = parent[childKey]; + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); } - } - context.parent.info.children = parent; - return parent; - } -} -module.exports = getFilterDeep; + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; -/***/ }), + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } -/***/ 14850: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; -"use strict"; + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; -var getEachDeep = __nccwpck_require__(47016); + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; -function getFindDeep(_) { - var eachDeep = getEachDeep(_); + this._strip(); - function findDeep(obj, predicate, options) { - predicate = _.iteratee(predicate); - if (!options) { - options = {}; + var res; + if (this.length > 1) { + res = 1; } else { - options = _.cloneDeep(options); - if (options.leafsOnly !== undefined) { - options.leavesOnly = options.leafsOnly; + if (negative) { + num = -num; } - } - options = _.merge( - { - checkCircular: false, - leavesOnly: options.childrenPath === undefined, - pathFormat: 'string', - }, - options - ); + assert(num <= 0x3ffffff, 'Number is too big'); - var eachDeepOptions = { - pathFormat: options.pathFormat, - checkCircular: options.checkCircular, - ownPropertiesOnly: options.ownPropertiesOnly, - childrenPath: options.childrenPath, - includeRoot: options.includeRoot, - rootIsChildren: options.rootIsChildren, - callbackAfterIterate: false, - leavesOnly: options.leavesOnly, - }; + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; - var res; + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; - eachDeep( - obj, - function (value, key, parent, context) { - if (predicate(value, key, parent, context)) { - res = { value: value, key: key, parent: parent, context: context }; - return context['break'](); - } - }, - eachDeepOptions - ); + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; return res; - } - return findDeep; -} + }; -module.exports = getFindDeep; + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; -/***/ }), + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; -/***/ 73970: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; -"use strict"; + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; -var getFindDeep = __nccwpck_require__(14850); + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; -function getFindPathDeep(_) { - var findDeep = getFindDeep(_); - function findPathDeep(obj, predicate, options) { - var res = findDeep(obj, predicate, options); - return res && res.context.path; - } - return findPathDeep; -} + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; -module.exports = getFindPathDeep; + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; -/***/ }), + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; -/***/ 84392: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; -"use strict"; + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; -var getFindDeep = __nccwpck_require__(14850); + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; -function getFindValueDeep(_) { - var findDeep = getFindDeep(_); - function findValueDeep(obj, predicate, options) { - var res = findDeep(obj, predicate, options); - return res && res.value; - } - return findValueDeep; -} + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; -module.exports = getFindValueDeep; + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; -/***/ }), + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; -/***/ 47164: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; -"use strict"; + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; -var getEachDeep = __nccwpck_require__(47016); + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; -function getForEachDeep(_) { - return getEachDeep(_); -} + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; -module.exports = getForEachDeep; + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; -/***/ }), + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; -/***/ 13953: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; -"use strict"; + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; -var getEachDeep = __nccwpck_require__(47016); + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; -function getIndex(_) { - var eachDeep = getEachDeep(_); + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; - function index(obj, options) { - options = _.merge( - { - checkCircular: false, - includeCircularPath: true, - leavesOnly: !options || options.childrenPath === undefined, - }, - options || {} - ); - if (options && options.leafsOnly !== undefined) { - options.leavesOnly = options.leafsOnly; - } - var eachDeepOptions = { - pathFormat: 'string', - checkCircular: options.checkCircular, - ownPropertiesOnly: options.ownPropertiesOnly, - includeRoot: options.includeRoot, - childrenPath: options.childrenPath, - rootIsChildren: options.rootIsChildren, - leavesOnly: options.leavesOnly, - }; - var res = {}; - eachDeep( - obj, - function (value, key, parent, context) { - if (!context.isCircular || options.includeCircularPath) { - if (context.path !== undefined) { - res[context.path] = value; - } - } - }, - eachDeepOptions - ); - return res; + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); } - return index; -} -module.exports = getIndex; + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; -/***/ }), + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); -/***/ 91152: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is a BN v4 instance + r.strip(); + } else { + // r is a BN v5 instance + r._strip(); + } + } -"use strict"; + return r; + }; + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; -var getPaths = __nccwpck_require__(49633); + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; -function getKeysDeep(_) { - return getPaths(_); -} + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); -module.exports = getKeysDeep; + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; -/***/ }), + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } -/***/ 86139: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; -"use strict"; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; -var getReduceDeep = __nccwpck_require__(97878); + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } -function getMapDeep(_) { - var reduceDeep = getReduceDeep(_); + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; - function mapDeep(obj, iteratee, options) { - iteratee = _.iteratee(iteratee); - return reduceDeep( - obj, - function (acc, value, key, parentValue, context) { - acc.push(iteratee(value, key, parentValue, context)); - return acc; - }, - [], - options - ); + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } - return mapDeep; -} - -module.exports = getMapDeep; - - -/***/ }), + inherits(P224, MPrime); -/***/ 28192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); -"use strict"; + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; -var getPathToString = __nccwpck_require__(69937); -var getEachDeep = __nccwpck_require__(47016); + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; -function getMapKeysDeep(_) { - var eachDeep = getEachDeep(_); - var pathToString = getPathToString(_); - function mapKeysDeep(obj, iteratee, options) { - if ( options === void 0 ) options = {}; + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; - iteratee = _.iteratee(iteratee); - options.cloneDeep = options.cloneDeep || _.cloneDeep; - options.callbackAfterIterate = false; - var newPaths = []; + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; - eachDeep( - obj, - function (value, key, parent, context) { - if (key === undefined) { - return; - } - var newKey = iteratee(value, key, parent, context) + ''; - if (newKey === key) { - return; - } - var oldPath = context.path; - var oldPathStr = - options.pathFormat === 'array' ? JSON.stringify(oldPath) : oldPath; - var newPath = - options.pathFormat === 'array' - ? (context.parent.path || []).concat( (context.childrenPath || []), - [newKey] ) - : pathToString([newKey], context.parent.path, context.childrenPath); - var newPathStr = - options.pathFormat === 'array' ? JSON.stringify(newPath) : newPath; - if (!newPaths[context.depth - 1]) { - newPaths[context.depth - 1] = []; - } - newPaths[context.depth - 1].push({ - oldPath: oldPath, - oldPathStr: oldPathStr, - newPath: newPath, - newPathStr: newPathStr, - }); - }, - options - ); - var res = options.cloneDeep(obj); + return prime; + }; - var d = newPaths.length; - var loop = function () { - if (!newPaths[d]) { - return; - } - var overwritten = {}; - newPaths[d].forEach(function (ref) { - var oldPath = ref.oldPath; - var oldPathStr = ref.oldPathStr; - var newPath = ref.newPath; - var newPathStr = ref.newPathStr; + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } - var value; - if (Object.prototype.hasOwnProperty.call(overwritten, oldPathStr)) { - value = overwritten[oldPathStr]; - delete overwritten[oldPathStr]; - } else { - value = _.get(res, oldPath); - if (value === undefined && !_.has(res, oldPath)) { - return; - } - _.unset(res, oldPath); - } - if ( - _.has(res, newPath) && - !Object.prototype.hasOwnProperty.call(overwritten, newPathStr) - ) { - overwritten[newPathStr] = _.get(res, newPath); - } - _.set(res, newPath, value); - }); - }; + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; - while (d--) loop(); - return res; - } - return mapKeysDeep; -} + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; -module.exports = getMapKeysDeep; + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; -/***/ }), + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } -/***/ 49743: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this.m.sub(a)._forceRed(this); + }; -"use strict"; + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; -var getEachDeep = __nccwpck_require__(47016); + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); -function getMapValuesDeep(_) { - var eachDeep = getEachDeep(_); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; - function mapValuesDeep(obj, iteratee, options) { - iteratee = _.iteratee(iteratee); - var res = Array.isArray(obj) ? [] : _.isObject(obj) ? {} : _.clone(obj); - var skipChildren; + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); - eachDeep( - obj, - function (value, key, parent, context) { - // if (!context.skipChildren) { - context.skipChildren = function (skip) { - skipChildren = skip; - }; - // } - skipChildren = undefined; - var r = iteratee(value, key, parent, context); - if (!context.isLeaf && skipChildren === undefined) { - skipChildren = - value !== r && Array.isArray(value) != Array.isArray(r); - } - if (context.path !== undefined) { - _.set(res, context.path, r); - } else { - res = r; - } - if (skipChildren) { - return false; - } - }, - options - ); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } return res; - } - return mapValuesDeep; -} + }; -module.exports = getMapValuesDeep; + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; -/***/ }), + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; -/***/ 81192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; -"use strict"; + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); -var getFilterDeep = __nccwpck_require__(79175); -var getPathMatches = __nccwpck_require__(8127); + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); -function getOmitDeep(_) { - var pathMatches = getPathMatches(_); - var filterDeep = getFilterDeep(_); + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } - function omitDeep(obj, paths, options) { - options = _.merge( - { - invert: false, - }, - options || {} - ); - var isOmit = !options.invert; - options = _.merge( - { - onMatch: { - cloneDeep: false, - skipChildren: false, - keepIfEmpty: !isOmit, - }, - onNotMatch: { - cloneDeep: false, - skipChildren: false, - keepIfEmpty: isOmit, - }, - }, - options - ); - options.leavesOnly = false; - options.childrenPath = undefined; - options.includeRoot = undefined; - options.pathFormat = 'array'; - options.onTrue = options.invert ? options.onMatch : options.onNotMatch; - options.onFalse = options.invert ? options.onNotMatch : options.onMatch; + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); - var test = function (value, key, parent, context) { - if (pathMatches(context.path, paths) !== false) { - return options.invert; - } else { - return !options.invert; - } - }; - return filterDeep(obj, test, options); - } - return omitDeep; -} + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); -module.exports = getOmitDeep; + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } -/***/ }), + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); -/***/ 8127: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } -"use strict"; + return r; + }; + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; -var getPathToString = __nccwpck_require__(69937); + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); -function getPathMatches(_) { - var pathToString = getPathToString(_); - function pathMatches(path, paths) { - var pathString; - var pathArray; - if (_.isString(path)) { - pathString = path; - } else { - pathArray = path; + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); } - if (!Array.isArray(paths)) { - paths = [paths]; - } else { - paths = _.cloneDeep(paths); + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; } - for (var i = 0; i < paths.length; i++) { - if (_.isString(paths[i])) { - paths[i] = _.toPath(paths[i]); - } - if (Array.isArray(paths[i])) { - if (pathArray === undefined) { - pathArray = _.toPath(pathString); - } - if ( - pathArray.length >= paths[i].length && - _.isEqual(_.takeRight(pathArray, paths[i].length), paths[i]) - ) { - // console.log('path matched'); - return paths[i]; - } - } else if (paths[i] instanceof RegExp) { - if (pathString === undefined) { - pathString = pathToString(path); + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); } - if (paths[i].test(pathString)) { - // console.log('regex matched', paths[i]); - return paths[i]; + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; } - } else { - throw new Error( - 'To match path use only string/regex or array of them.' - ); - } - } - // console.log('matched nothing'); - return false; - } - return pathMatches; -} -getPathMatches.notChainable = true; + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; -module.exports = getPathMatches; + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + return res; + }; -/***/ }), + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); -/***/ 69937: -/***/ ((module) => { + return r === num ? r.clone() : r; + }; -"use strict"; + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + // + // Montgomery method engine + // -var rxArrIndex = /\D/; -var rxVarName = /^[a-zA-Z_$]+([\w_$]*)$/; -var rxQuot = /"/g; + BN.mont = function mont (num) { + return new Mont(num); + }; -function joinPaths() { - var paths = [], len = arguments.length; - while ( len-- ) paths[ len ] = arguments[ len ]; + function Mont (m) { + Red.call(this, m); - return paths.reduce( - function (acc, p) { return acc ? (!p || p.startsWith('[') ? ("" + acc + p) : (acc + "." + p)) : p; }, - '' - ); -} + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } -function getPathToString(_) { - function pathToString(path) { - var prefixes = [], len = arguments.length - 1; - while ( len-- > 0 ) prefixes[ len ] = arguments[ len + 1 ]; + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); - prefixes = prefixes.filter(function (p) { return p !== undefined; }); - if (_.isString(path)) { return joinPaths.apply(void 0, prefixes.concat( [path] )); } - if (!Array.isArray(path)) { return undefined; } - prefixes = joinPaths.apply(void 0, prefixes); - return path.reduce(function (acc, value) { - var type = typeof value; - if (type === 'number') { - if (value < 0 || value % 1 !== 0) { - return (acc + "[\"" + value + "\"]"); - } else { - return (acc + "[" + value + "]"); - } - } else if (type !== 'string') { - return (acc + "[\"" + value + "\"]"); - } else if (!value) { - return (acc + "[\"\"]"); - } - if (!rxArrIndex.test(value)) { - return (acc + "[" + value + "]"); - } - if (rxVarName.test(value)) { - if (acc) { - return (acc + "." + value); - } else { - return ("" + acc + value); - } - } - return (acc + "[\"" + (value.replace(rxQuot, '\\"')) + "\"]"); - }, prefixes); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); } - return pathToString; -} - -getPathToString.notChainable = true; + inherits(Mont, Red); -module.exports = getPathToString; + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; -/***/ }), + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } -/***/ 49633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; -"use strict"; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; -var getEachDeep = __nccwpck_require__(47016); + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); -function getPaths(_) { - var eachDeep = getEachDeep(_); - function paths(obj, options) { - if (options && options.leafsOnly !== undefined) { - options.leavesOnly = options.leafsOnly; + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); } - options = _.merge( - { - checkCircular: false, - includeCircularPath: true, - leavesOnly: !options || options.childrenPath === undefined, - pathFormat: 'string', - }, - options || {} - ); - var eachDeepOptions = { - pathFormat: options.pathFormat, - checkCircular: options.checkCircular, - ownPropertiesOnly: options.ownPropertiesOnly, - includeRoot: options.includeRoot, - childrenPath: options.childrenPath, - rootIsChildren: options.rootIsChildren, - leavesOnly: options.leavesOnly, - }; - var res = []; - eachDeep( - obj, - function (value, key, parent, context) { - if (!context.isCircular || options.includeCircularPath) { - if (context.path !== undefined) { - res.push(context.path); - } - } - }, - eachDeepOptions - ); - return res; - } - return paths; -} -module.exports = getPaths; + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); /***/ }), -/***/ 64541: +/***/ 96425: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var getOmitDeep = __nccwpck_require__(81192); +var getMixOrPatchIn = __nccwpck_require__(22514); +var getCondense = __nccwpck_require__(15631); -function getPickDeep(_) { - var omitDeep = getOmitDeep(_); - function pickDeep(obj, paths, options) { - options = _.merge( - { - invert: false, - }, - options || {} - ); - options.invert = true; - return omitDeep(obj, paths, options); - } - return pickDeep; +/* build/tpl */ + +function addCondense(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('condense', getCondense(), !getCondense.notChainable); } -module.exports = getPickDeep; +module.exports = addCondense; /***/ }), -/***/ 97878: +/***/ 25591: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var getEachDeep = __nccwpck_require__(47016); +var getMixOrPatchIn = __nccwpck_require__(22514); +var getCondenseDeep = __nccwpck_require__(6198); -function getReduceDeep(_) { - var eachDeep = getEachDeep(_); +/* build/tpl */ - function reduceDeep(obj, iteratee, accumulator, options) { - var accumulatorInited = accumulator !== undefined; - eachDeep( - obj, - function (value, key, parent, context) { - if (!accumulatorInited) { - accumulator = value; - accumulatorInited = true; - } else { - accumulator = iteratee(accumulator, value, key, parent, context); - } - }, - options - ); - return accumulator; - } - return reduceDeep; +function addCondenseDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('condenseDeep', getCondenseDeep(_), !getCondenseDeep.notChainable); } -module.exports = getReduceDeep; +module.exports = addCondenseDeep; /***/ }), -/***/ 34949: +/***/ 39683: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var getFindDeep = __nccwpck_require__(14850); +var getMixOrPatchIn = __nccwpck_require__(22514); +var getEachDeep = __nccwpck_require__(47016); -function getSomeDeep(_) { - var findDeep = getFindDeep(_); - function someDeep(obj, predicate, options) { - return !!findDeep(obj, predicate, options); - } - return someDeep; +/* build/tpl */ + +function addEachDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('eachDeep', getEachDeep(_), !getEachDeep.notChainable); } -module.exports = getSomeDeep; +module.exports = addEachDeep; /***/ }), -/***/ 55267: +/***/ 88701: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var getPathToString = __nccwpck_require__(69937); -var isObject = __nccwpck_require__(86564); - -var rxVarName = /^[a-zA-Z_$]+([\w_$]*)$/; -var rxQuot = /"/g; -var has = Object.prototype.hasOwnProperty; - -function getIterate(_) { - var pathToString = getPathToString(_); - - function iterate(item) { - var options = item.options; - var obj = item.obj; - var callback = item.callback; - options.pathFormatArray = options.pathFormat == 'array'; - item.depth = 0; - - var broken = false; - var breakIt = function () { - broken = true; - return false; - }; - - while (item) { - if (broken) { break; } - if (!item.inited) { - item.inited = true; - item.info = describeValue(item.value, options.ownPropertiesOnly); - - if (options.checkCircular) { - item.circularParentIndex = -1; - item.circularParent = null; - item.isCircular = false; - if (item.info.isObject && !item.info.isEmpty) { - var parent = item.parent; - while (parent) { - if (parent.value === item.value) { - item.isCircular = true; - item.circularParent = parent; - item.circularParentIndex = item.depth - parent.depth - 1; - break; - } - parent = parent.parent; - } - } - } +var getMixOrPatchIn = __nccwpck_require__(22514); +var getExists = __nccwpck_require__(84282); - item.children = []; - if (options.childrenPath) { - options.childrenPath.forEach(function (cp, i) { - var children = _.get(item.value, cp); - var info = describeValue(children, options.ownPropertiesOnly); - if (!info.isEmpty) { - item.children.push([ - cp, - options.strChildrenPath[i], - children, - info ]); - } - }); - } +/* build/tpl */ - item.isLeaf = - item.isCircular || - (options.childrenPath !== undefined && !item.children.length) || - !item.info.isObject || - item.info.isEmpty; +function addExists(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('exists', getExists(_), !getExists.notChainable); +} - item.needCallback = - (item.depth || options.includeRoot) && - (!options.leavesOnly || item.isLeaf); +module.exports = addExists; - if (item.needCallback) { - var contextReader = new ContextReader(obj, options, breakIt); - contextReader.setItem(item, false); - try { - item.res = callback( - item.value, - item.key, - item.parent && item.parent.value, - contextReader - ); - } catch (err) { - if (err.message) { - err.message += - '\ncallback failed before deep iterate at:\n' + - pathToString(item.path); - } - throw err; - } - } +/***/ }), - if (broken) { - break; - } +/***/ 91422: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (item.res !== false) { - if (!broken && !item.isCircular && item.info.isObject) { - if ( - options.childrenPath !== undefined && - (item.depth || !options.rootIsChildren) - ) { - item.childrenItems = []; - if (item.children.length) { - item.children.forEach(function (ref) { - var cp = ref[0]; - var scp = ref[1]; - var children = ref[2]; - var info = ref[3]; +"use strict"; - item.childrenItems = ( item.childrenItems ).concat( (info.isArray - ? getElements(item, children, options, cp, scp) - : getOwnChildren(item, children, options, cp, scp)) ); - }); - } - } else { - item.childrenItems = item.info.isArray - ? getElements(item, item.value, options, [], '') - : getOwnChildren(item, item.value, options, [], ''); - } - } - } - item.currentChildIndex = -1; - } - if ( - item.childrenItems && - item.currentChildIndex < item.childrenItems.length - 1 - ) { - item.currentChildIndex++; - item.childrenItems[item.currentChildIndex].parentItem = item; - item = item.childrenItems[item.currentChildIndex]; - continue; - } +var getMixOrPatchIn = __nccwpck_require__(22514); +var getFilterDeep = __nccwpck_require__(79175); - if (item.needCallback && options.callbackAfterIterate) { - var contextReader$1 = new ContextReader(obj, options, breakIt); - contextReader$1.setItem(item, true); +/* build/tpl */ - try { - callback( - item.value, - item.key, - item.parent && item.parent.value, - contextReader$1 - ); - } catch (err) { - if (err.message) { - err.message += - '\ncallback failed after deep iterate at:\n' + - pathToString(item.path); - } +function addFilterDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('filterDeep', getFilterDeep(_), !getFilterDeep.notChainable); +} - throw err; - } - } - item = item.parentItem; - } - } +module.exports = addFilterDeep; - return iterate; - function getElements(item, children, options, childrenPath, strChildrenPath) { - var strChildPathPrefix; - if (!options.pathFormatArray) { - strChildPathPrefix = item.strPath || ''; +/***/ }), - if ( - strChildrenPath && - strChildPathPrefix && - !strChildrenPath.startsWith('[') - ) { - strChildPathPrefix += '.'; - } - strChildPathPrefix += strChildrenPath || ''; - } - var res = []; - for (var i = 0; i < children.length; i++) { - var val = children[i]; - if (val === undefined && !(i in children)) { - continue; - } - var strChildPath = (void 0); - var pathFormatString = !options.pathFormatArray; - if (pathFormatString) { - strChildPath = strChildPathPrefix + "[" + i + "]"; - } - res.push({ - value: val, - key: i + '', - path: (item.path || []).concat( childrenPath, [i + '']), - strPath: strChildPath, - depth: item.depth + 1, - parent: { - value: item.value, - key: item.key, - path: pathFormatString ? item.strPath : item.path, - parent: item.parent, - depth: item.depth, - info: item.info, - }, - childrenPath: (childrenPath.length && childrenPath) || undefined, - strChildrenPath: strChildrenPath || undefined, - }); - } - return res; - } +/***/ 73592: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function getOwnChildren( - item, - children, - options, - childrenPath, - strChildrenPath - ) { - var strChildPathPrefix; - if (!options.pathFormatArray) { - strChildPathPrefix = item.strPath || ''; +"use strict"; - if ( - strChildrenPath && - strChildPathPrefix && - !strChildrenPath.startsWith('[') - ) { - strChildPathPrefix += '.'; - } - strChildPathPrefix += strChildrenPath || ''; - } - var res = []; - var pathFormatString = !options.pathFormatArray; - for (var childKey in children) { - if (options.ownPropertiesOnly && !has.call(children, childKey)) { - continue; - } - var strChildPath = (void 0); - if (pathFormatString) { - if (rxVarName.test(childKey)) { - if (strChildPathPrefix) { - strChildPath = strChildPathPrefix + "." + childKey; - } else { - strChildPath = "" + childKey; - } - } else { - strChildPath = strChildPathPrefix + "[\"" + (childKey.replace( - rxQuot, - '\\"' - )) + "\"]"; - } - } +var getMixOrPatchIn = __nccwpck_require__(22514); +var getFindDeep = __nccwpck_require__(14850); - res.push({ - value: children[childKey], - key: childKey, - path: (item.path || []).concat( childrenPath, [childKey]), - strPath: strChildPath, - depth: item.depth + 1, - parent: { - value: item.value, - key: item.key, - path: pathFormatString ? item.strPath : item.path, - parent: item.parent, - depth: item.depth, - info: item.info, - }, - childrenPath: (childrenPath.length && childrenPath) || undefined, - strChildrenPath: strChildrenPath || undefined, - }); - } +/* build/tpl */ - return res; - } +function addFindDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('findDeep', getFindDeep(_), !getFindDeep.notChainable); } -var ContextReader = function ContextReader(obj, options, breakIt) { - this.obj = obj; - this._options = options; - this['break'] = breakIt; -}; +module.exports = addFindDeep; -var prototypeAccessors = { path: { configurable: true },parent: { configurable: true },parents: { configurable: true },depth: { configurable: true },isLeaf: { configurable: true },isCircular: { configurable: true },circularParentIndex: { configurable: true },circularParent: { configurable: true },childrenPath: { configurable: true },info: { configurable: true } }; -ContextReader.prototype.setItem = function setItem (item, afterIterate) { - this._item = item; - this.afterIterate = afterIterate; -}; -prototypeAccessors.path.get = function () { - return this._options.pathFormatArray ? this._item.path : this._item.strPath; -}; -prototypeAccessors.parent.get = function () { - return this._item.parent; -}; +/***/ }), -prototypeAccessors.parents.get = function () { - if (!this._item._parents) { - this._item._parents = []; - var curParent = this._item.parent; - while (curParent) { - this._item._parents[curParent.depth] = curParent; - curParent = curParent.parent; - } - } - return this._item._parents; -}; -prototypeAccessors.depth.get = function () { - return this._item.depth; -}; +/***/ 41368: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -prototypeAccessors.isLeaf.get = function () { - return this._item.isLeaf; -}; +"use strict"; -prototypeAccessors.isCircular.get = function () { - return this._item.isCircular; -}; -prototypeAccessors.circularParentIndex.get = function () { - return this._item.circularParentIndex; -}; +var getMixOrPatchIn = __nccwpck_require__(22514); +var getFindPathDeep = __nccwpck_require__(73970); -prototypeAccessors.circularParent.get = function () { - return this._item.circularParent; -}; +/* build/tpl */ -prototypeAccessors.childrenPath.get = function () { - return ( - (this._options.childrenPath !== undefined && - (this._options.pathFormatArray - ? this._item.childrenPath - : this._item.strChildrenPath)) || - undefined - ); -}; +function addFindPathDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('findPathDeep', getFindPathDeep(_), !getFindPathDeep.notChainable); +} -prototypeAccessors.info.get = function () { - return this._item.info; -}; +module.exports = addFindPathDeep; -Object.defineProperties( ContextReader.prototype, prototypeAccessors ); -function isObjectEmpty(value, ownPropertiesOnly) { - for (var key in value) { - if (!ownPropertiesOnly || has.call(value, key)) { - return false; - } - } - return true; -} +/***/ }), -function describeValue(value, ownPropertiesOnly) { - var res = { isObject: isObject(value) }; - res.isArray = res.isObject && Array.isArray(value); - res.isEmpty = res.isArray - ? !value.length - : res.isObject - ? isObjectEmpty(value, ownPropertiesOnly) - : true; +/***/ 97447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return res; +"use strict"; + + +var getMixOrPatchIn = __nccwpck_require__(22514); +var getFindValueDeep = __nccwpck_require__(84392); + +/* build/tpl */ + +function addFindValueDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('findValueDeep', getFindValueDeep(_), !getFindValueDeep.notChainable); } -module.exports = getIterate; +module.exports = addFindValueDeep; /***/ }), -/***/ 22514: -/***/ ((module) => { +/***/ 31114: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -function getMixOrPatchIn(_) { - function mixOrPatchIn(name, method, chain) { - if (!_[name]) { - if (_.mixin) { - var patch = {}; - patch[name] = method; - _.mixin(patch, { chain: chain }); - } else { - _[name] = method; - } - } - return _; - } - return mixOrPatchIn; +var getMixOrPatchIn = __nccwpck_require__(22514); +var getForEachDeep = __nccwpck_require__(47164); + +/* build/tpl */ + +function addForEachDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('forEachDeep', getForEachDeep(_), !getForEachDeep.notChainable); } -module.exports = getMixOrPatchIn; +module.exports = addForEachDeep; /***/ }), -/***/ 86564: -/***/ ((module) => { +/***/ 99634: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); +var getMixOrPatchIn = __nccwpck_require__(22514); +var getIndex = __nccwpck_require__(13953); + +/* build/tpl */ + +function addIndex(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('index', getIndex(_), !getIndex.notChainable); } -module.exports = isObject; +module.exports = addIndex; /***/ }), -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { +/***/ 82400: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +var getMixOrPatchIn = __nccwpck_require__(22514); +var getKeysDeep = __nccwpck_require__(91152); -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +/* build/tpl */ - /* istanbul ignore next */ +function addKeysDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('keysDeep', getKeysDeep(_), !getKeysDeep.notChainable); +} - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } +module.exports = addKeysDeep; - this.name = 'Deprecation'; - } +/***/ }), + +/***/ 30547: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var getMixOrPatchIn = __nccwpck_require__(22514); +var getMapDeep = __nccwpck_require__(86139); + +/* build/tpl */ + +function addMapDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('mapDeep', getMapDeep(_), !getMapDeep.notChainable); } -exports.Deprecation = Deprecation; +module.exports = addMapDeep; /***/ }), -/***/ 11848: -/***/ ((module) => { +/***/ 51391: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var has = Object.prototype.hasOwnProperty - , prefix = '~'; - -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} +var getMixOrPatchIn = __nccwpck_require__(22514); +var getMapKeysDeep = __nccwpck_require__(28192); -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); +/* build/tpl */ - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; +function addMapKeysDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('mapKeysDeep', getMapKeysDeep(_), !getMapKeysDeep.notChainable); } -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} +module.exports = addMapKeysDeep; -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; +/***/ }), - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; +/***/ 13354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return emitter; -} +"use strict"; -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} +var getMixOrPatchIn = __nccwpck_require__(22514); +var getMapValuesDeep = __nccwpck_require__(49743); -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; +/* build/tpl */ - if (this._eventsCount === 0) return names; +function addMapValuesDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('mapValuesDeep', getMapValuesDeep(_), !getMapValuesDeep.notChainable); +} - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } +module.exports = addMapValuesDeep; - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - return names; -}; +/***/ }), -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; +/***/ 86835: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; +"use strict"; - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - return ee; -}; +var getMixOrPatchIn = __nccwpck_require__(22514); +var getOmitDeep = __nccwpck_require__(81192); -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; +/* build/tpl */ - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; +function addOmitDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('omitDeep', getOmitDeep(_), !getOmitDeep.notChainable); +} -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; +module.exports = addOmitDeep; - if (!this._events[evt]) return false; - var listeners = this._events[evt] - , len = arguments.length - , args - , i; +/***/ }), - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); +/***/ 41612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } +"use strict"; - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; +var getMixOrPatchIn = __nccwpck_require__(22514); +var getPathMatches = __nccwpck_require__(8127); - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); +/* build/tpl */ - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } +function addPathMatches(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('pathMatches', getPathMatches(_), !getPathMatches.notChainable); +} - listeners[i].fn.apply(listeners[i].context, args); - } - } - } +module.exports = addPathMatches; - return true; -}; -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; +/***/ }), -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; +/***/ 18017: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; +"use strict"; - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - var listeners = this._events[evt]; +var getMixOrPatchIn = __nccwpck_require__(22514); +var getPathToString = __nccwpck_require__(69937); - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } +/* build/tpl */ - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } +function addPathToString(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('pathToString', getPathToString(_), !getPathToString.notChainable); +} - return this; -}; +module.exports = addPathToString; -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } +/***/ }), - return this; -}; +/***/ 84397: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; +"use strict"; -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; +var getMixOrPatchIn = __nccwpck_require__(22514); +var getPaths = __nccwpck_require__(49633); -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; +/* build/tpl */ + +function addPaths(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('paths', getPaths(_), !getPaths.notChainable); } +module.exports = addPaths; + /***/ }), -/***/ 63287: -/***/ ((__unused_webpack_module, exports) => { +/***/ 83080: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +var getMixOrPatchIn = __nccwpck_require__(22514); +var getPickDeep = __nccwpck_require__(64541); -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ +/* build/tpl */ -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; +function addPickDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('pickDeep', getPickDeep(_), !getPickDeep.notChainable); } -function isPlainObject(o) { - var ctor,prot; +module.exports = addPickDeep; - 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; +/***/ 1643: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } +"use strict"; - // Most likely a plain Object - return true; + +var getMixOrPatchIn = __nccwpck_require__(22514); +var getReduceDeep = __nccwpck_require__(97878); + +/* build/tpl */ + +function addReduceDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('reduceDeep', getReduceDeep(_), !getReduceDeep.notChainable); } -exports.isPlainObject = isPlainObject; +module.exports = addReduceDeep; /***/ }), -/***/ 46014: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 55221: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Clone = __nccwpck_require__(85578); - -const Common = __nccwpck_require__(72448); +var getMixOrPatchIn = __nccwpck_require__(22514); +var getSomeDeep = __nccwpck_require__(34949); +/* build/tpl */ -const internals = { - annotations: Symbol('annotations') -}; +function addSomeDeep(_) { + var mixOrPatchIn = getMixOrPatchIn(_); + return mixOrPatchIn('someDeep', getSomeDeep(_), !getSomeDeep.notChainable); +} +module.exports = addSomeDeep; -exports.error = function (stripColorCodes) { - if (!this._original || - typeof this._original !== 'object') { +/***/ }), - return this.details[0].message; - } +/***/ 13503: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const redFgEscape = stripColorCodes ? '' : '\u001b[31m'; - const redBgEscape = stripColorCodes ? '' : '\u001b[41m'; - const endColor = stripColorCodes ? '' : '\u001b[0m'; +"use strict"; - const obj = Clone(this._original); - for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first - const pos = i + 1; - const error = this.details[i]; - const path = error.path; - let node = obj; - for (let j = 0; ; ++j) { - const seg = path[j]; +var addCondense = __nccwpck_require__(96425); +var addCondenseDeep = __nccwpck_require__(25591); +var addEachDeep = __nccwpck_require__(39683); +var addExists = __nccwpck_require__(88701); +var addFilterDeep = __nccwpck_require__(91422); +var addFindDeep = __nccwpck_require__(73592); +var addFindPathDeep = __nccwpck_require__(41368); +var addFindValueDeep = __nccwpck_require__(97447); +var addForEachDeep = __nccwpck_require__(31114); +var addIndex = __nccwpck_require__(99634); +var addKeysDeep = __nccwpck_require__(82400); +var addMapDeep = __nccwpck_require__(30547); +var addMapKeysDeep = __nccwpck_require__(51391); +var addMapValuesDeep = __nccwpck_require__(13354); +var addOmitDeep = __nccwpck_require__(86835); +var addPathMatches = __nccwpck_require__(41612); +var addPathToString = __nccwpck_require__(18017); +var addPaths = __nccwpck_require__(84397); +var addPickDeep = __nccwpck_require__(83080); +var addReduceDeep = __nccwpck_require__(1643); +var addSomeDeep = __nccwpck_require__(55221); - if (Common.isSchema(node)) { - node = node.clone(); // joi schemas are not cloned by hoek, we have to take this extra step - } +/* build/tpl */ - if (j + 1 < path.length && - typeof node[seg] !== 'string') { +function apply(_) { + addCondense(_); + addCondenseDeep(_); + addEachDeep(_); + addExists(_); + addFilterDeep(_); + addFindDeep(_); + addFindPathDeep(_); + addFindValueDeep(_); + addForEachDeep(_); + addIndex(_); + addKeysDeep(_); + addMapDeep(_); + addMapKeysDeep(_); + addMapValuesDeep(_); + addOmitDeep(_); + addPathMatches(_); + addPathToString(_); + addPaths(_); + addPickDeep(_); + addReduceDeep(_); + addSomeDeep(_); - node = node[seg]; - } - else { - const refAnnotations = node[internals.annotations] || { errors: {}, missing: {} }; - node[internals.annotations] = refAnnotations; + return _; +} - const cacheKey = seg || error.context.key; +module.exports = apply; - if (node[seg] !== undefined) { - refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || []; - refAnnotations.errors[cacheKey].push(pos); - } - else { - refAnnotations.missing[cacheKey] = pos; - } - break; - } - } - } +/***/ }), - const replacers = { - key: /_\$key\$_([, \d]+)_\$end\$_"/g, - missing: /"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g, - arrayIndex: /\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g, - specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g - }; +/***/ 15631: +/***/ ((module) => { - let message = internals.safeStringify(obj, 2) - .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`) - .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`) - .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`) - .replace(replacers.specials, ($0, $1) => $1); +"use strict"; - message = `${message}\n${redFgEscape}`; - for (let i = 0; i < this.details.length; ++i) { - const pos = i + 1; - message = `${message}\n[${pos}] ${this.details[i].message}`; +function getCondense(_) { + function condense(arr) { + var indexes = []; + for (var i = 0; i < arr.length; i++) { + if (!(i in arr)) { + indexes.push(i); + } } + var length = indexes.length; - message = message + endColor; - - return message; -}; - - -// Inspired by json-stringify-safe + while (length--) { + arr.splice(indexes[length], 1); + } + return arr; + } + return condense; +} -internals.safeStringify = function (obj, spaces) { +module.exports = getCondense; - return JSON.stringify(obj, internals.serializer(), spaces); -}; +/***/ }), -internals.serializer = function () { +/***/ 6198: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const keys = []; - const stack = []; +"use strict"; - const cycleReplacer = (key, value) => { - if (stack[0] === value) { - return '[Circular ~]'; - } +var getCondense = __nccwpck_require__(15631); +var getEachDeep = __nccwpck_require__(47016); - return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; +function getCondenseDeep(_) { + var eachDeep = getEachDeep(_); + var condense = getCondense(); + var _each = _.each || _.forArray; + function condenseDeep(obj, options) { + options = _.merge( + { + checkCircular: false, + }, + options || {} + ); + var eachDeepOptions = { + checkCircular: options.checkCircular, + ownPropertiesOnly: options.ownPropertiesOnly, }; + var arrays = []; + //console.log('condenseDeep → eachDeep'); + eachDeep( + obj, + function (value, key, parent, context) { + if (!context.isCircular && Array.isArray(value)) { arrays.push(value); } + }, + eachDeepOptions + ); + if (Array.isArray(obj)) { arrays.push(obj); } + _each(arrays, condense); + return obj; + } + return condenseDeep; +} - return function (key, value) { +module.exports = getCondenseDeep; - if (stack.length > 0) { - const thisPos = stack.indexOf(this); - if (~thisPos) { - stack.length = thisPos + 1; - keys.length = thisPos + 1; - keys[thisPos] = key; - } - else { - stack.push(this); - keys.push(key); - } - if (~stack.indexOf(value)) { - value = cycleReplacer.call(this, key, value); - } - } - else { - stack.push(value); - } +/***/ }), - if (value) { - const annotations = value[internals.annotations]; - if (annotations) { - if (Array.isArray(value)) { - const annotated = []; +/***/ 47016: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (let i = 0; i < value.length; ++i) { - if (annotations.errors[i]) { - annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`); - } +"use strict"; - annotated.push(value[i]); - } - value = annotated; - } - else { - for (const errorKey in annotations.errors) { - value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey]; - value[errorKey] = undefined; - } +var getIterate = __nccwpck_require__(55267); - for (const missingKey in annotations.missing) { - value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__'; - } - } +function getEachDeep(_) { + var iterate = getIterate(_); - return value; - } + function eachDeep(obj, callback, options) { + if (callback === undefined) { callback = _.identity; } + options = _.merge( + { + includeRoot: !Array.isArray(obj), + pathFormat: 'string', + checkCircular: false, + leavesOnly: false, + ownPropertiesOnly: true, // + }, + options || {} + ); + if (options.childrenPath !== undefined) { + if (!options.includeRoot && options.rootIsChildren === undefined) { + options.rootIsChildren = Array.isArray(obj); + } + if ( + !_.isString(options.childrenPath) && + !Array.isArray(options.childrenPath) + ) { + throw Error('childrenPath can be string or array'); + } else { + if (_.isString(options.childrenPath)) { + options.childrenPath = [options.childrenPath]; } - - if (value === Infinity || - value === -Infinity || - Number.isNaN(value) || - typeof value === 'function' || - typeof value === 'symbol') { - - return '[' + value.toString() + ']'; + options.strChildrenPath = options.childrenPath; + options.childrenPath = []; + for (var i = options.strChildrenPath.length - 1; i >= 0; i--) { + options.childrenPath[i] = _.toPath(options.strChildrenPath[i]); } + } + } + iterate({ + value: obj, + callback: callback, + options: options, + obj: obj, + }); + return obj; + } + return eachDeep; +} - return value; - }; -}; +module.exports = getEachDeep; /***/ }), -/***/ 95184: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 84282: +/***/ ((module) => { "use strict"; -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const DeepEqual = __nccwpck_require__(55801); -const Merge = __nccwpck_require__(60445); - -const Cache = __nccwpck_require__(63355); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Extend = __nccwpck_require__(86680); -const Manifest = __nccwpck_require__(87997); -const Messages = __nccwpck_require__(86103); -const Modify = __nccwpck_require__(81290); -const Ref = __nccwpck_require__(73838); -const Trace = __nccwpck_require__(43171); -const Validator = __nccwpck_require__(91804); -const Values = __nccwpck_require__(71944); - - -const internals = {}; - - -internals.Base = class { +function getExists(_) { + function exists(obj, path) { + path = Array.isArray(path) ? _.clone(path) : _.toPath(path); + var key = path.pop(); + var parent = path.length ? _.get(obj, path) : obj; + return parent !== undefined && key in parent; + } + return exists; +} - constructor(type) { +getExists.notChainable = true; - // Naming: public, _private, $_extension, $_mutate{action} +module.exports = getExists; - this.type = type; - this.$_root = null; - this._definition = {}; - this._reset(); - } +/***/ }), - _reset() { +/***/ 79175: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._ids = new Modify.Ids(); - this._preferences = null; - this._refs = new Ref.Manager(); - this._cache = null; +"use strict"; - this._valids = null; - this._invalids = null; - this._flags = {}; - this._rules = []; - this._singleRules = new Map(); // The rule options passed for non-multi rules +var getCondense = __nccwpck_require__(15631); +var isObject = __nccwpck_require__(86564); +var getEachDeep = __nccwpck_require__(47016); - this.$_terms = {}; // Hash of arrays of immutable objects (extended by other types) +function getFilterDeep(_) { + var eachDeep = getEachDeep(_); + var condense = getCondense(); - this.$_temp = { // Runtime state (not cloned) - ruleset: null, // null: use last, false: error, number: start position - whens: {} // Runtime cache of generated whens - }; + function filterDeep(obj, predicate, options) { + predicate = _.iteratee(predicate); + if (!options) { + options = {}; + } else { + options = _.cloneDeep(options); + if (options.leafsOnly !== undefined) { + options.leavesOnly = options.leafsOnly; + } } + if (!options.onTrue) { + options.onTrue = {}; + } + if (!options.onFalse) { + options.onFalse = {}; + } + if (!options.onUndefined) { + options.onUndefined = {}; + } + if (options.childrenPath !== undefined) { + if (options.onTrue.skipChildren === undefined) { + options.onTrue.skipChildren = false; + } + if (options.onUndefined.skipChildren === undefined) { + options.onUndefined.skipChildren = false; + } + if (options.onFalse.skipChildren === undefined) { + options.onFalse.skipChildren = false; + } - // Manifest - - describe() { - - Assert(typeof Manifest.describe === 'function', 'Manifest functionality disabled'); - return Manifest.describe(this); + if (options.onTrue.cloneDeep === undefined) { + options.onTrue.cloneDeep = true; + } + if (options.onUndefined.cloneDeep === undefined) { + options.onUndefined.cloneDeep = true; + } + if (options.onFalse.cloneDeep === undefined) { + options.onFalse.cloneDeep = true; + } } + options = _.merge( + { + checkCircular: false, + keepCircular: true, + //replaceCircularBy: , + leavesOnly: options.childrenPath === undefined, + condense: true, + cloneDeep: _.cloneDeep, + pathFormat: 'string', + onTrue: { skipChildren: true, cloneDeep: true, keepIfEmpty: true }, + onUndefined: { + skipChildren: false, + cloneDeep: false, + keepIfEmpty: false, + }, + onFalse: { + skipChildren: true, + cloneDeep: false, + keepIfEmpty: false, + }, + }, + options + ); - // Rules + var eachDeepOptions = { + pathFormat: options.pathFormat, + checkCircular: options.checkCircular, + childrenPath: options.childrenPath, + includeRoot: options.includeRoot, + rootIsChildren: options.rootIsChildren, + ownPropertiesOnly: options.ownPropertiesOnly, + callbackAfterIterate: true, + leavesOnly: false, + }; + var resIsArray = Array.isArray(obj); + var res = resIsArray ? [] : isObject(obj) ? {} : null; + var toCondense = options.condense ? [] : false; + eachDeep( + obj, + function (value, key, parent, context) { + if (!context.afterIterate) { + context.info._filterDeep = {}; + if (!context.isCircular) { + var reply = + !options.leavesOnly || context.isLeaf + ? predicate(value, key, parent, context) + : undefined; - allow(...values) { + if (!isObject(reply)) { + if (reply === undefined) { + reply = options.onUndefined; + } else if (reply) { + reply = options.onTrue; + } else { + reply = options.onFalse; + } + } + context.info._filterDeep.reply = reply; + context.info._filterDeep.empty = + reply.empty === undefined ? true : reply.empty; - Common.verifyFlat(values, 'allow'); - return this._values(values, '_valids'); - } + if (reply.keepIfEmpty || !reply.skipChildren) { + if (options.cloneDeep && reply.cloneDeep) { + if (context.path !== undefined) { + var children = takeResultParent(context, res); + context.info._filterDeep.res = children[ + key + ] = options.cloneDeep(value); + } else { + context.info._filterDeep.res = res = options.cloneDeep(value); + } + } else { + if (context.path !== undefined) { + var children$1 = takeResultParent(context, res); + context.info._filterDeep.res = children$1[key] = context.info + .isArray + ? [] + : context.info.isObject + ? {} + : value; + } else { + context.info._filterDeep.res = res = context.info.isArray + ? [] + : context.info.isObject + ? {} + : value; + } + } + } + return !reply.skipChildren; + } else { + var children$2 = takeResultParent(context, res); + if (!options.keepCircular) { + delete children$2[key]; + if ( + toCondense && + ((children$2 === context.parent.info._filterDeep.res && + context.parent.info.isArray) || + Array.isArray(children$2)) && + !context.parent.info._filterDeep.isSparse + ) { + context.parent.info._filterDeep.isSparse = true; + toCondense.push(context.parent.info); + } - alter(targets) { + context.info._filterDeep.excluded = true; + } else { + context.info._filterDeep.res = children$2[key] = + 'replaceCircularBy' in options + ? options.replaceCircularBy + : context.circularParent.path !== undefined + ? context.circularParent.info._filterDeep.res + : res; + } + return false; + } + } else if (context.afterIterate && !context.isCircular) { + var reply$1 = context.info._filterDeep.reply; - Assert(targets && typeof targets === 'object' && !Array.isArray(targets), 'Invalid targets argument'); - Assert(!this._inRuleset(), 'Cannot set alterations inside a ruleset'); + if (context.info._filterDeep.empty && !reply$1.keepIfEmpty) { + if (context.path === undefined) { + res = null; + } else { + var children$3 = takeResultParent(context, res); + delete children$3[key]; + if ( + toCondense && + ((children$3 === context.parent.info._filterDeep.res && + context.parent.info.isArray) || + Array.isArray(children$3)) && + !context.parent.info._filterDeep.isSparse + ) { + context.parent.info._filterDeep.isSparse = true; + toCondense.push(context.parent.info); + } + context.info._filterDeep.excluded = true; + } + } else { + var parent$1 = context.parent; + while (parent$1) { + // if (!parent.info._filterDeep) { + // parent.info._filterDeep = {}; + // } + if (!parent$1.info._filterDeep.reply) { + parent$1.info._filterDeep.reply = options.onUndefined; + } + if (!parent$1.info._filterDeep.empty) { + break; + } + parent$1.info._filterDeep.empty = false; + parent$1 = parent$1.parent; + } + } - const obj = this.clone(); - obj.$_terms.alterations = obj.$_terms.alterations || []; - for (const target in targets) { - const adjuster = targets[target]; - Assert(typeof adjuster === 'function', 'Alteration adjuster for', target, 'must be a function'); - obj.$_terms.alterations.push({ target, adjuster }); + return; } + }, + eachDeepOptions + ); - obj.$_temp.ruleset = false; - return obj; + if (toCondense) { + for (var i = 0; i < toCondense.length; i++) { + var info = toCondense[i]; + if (info._filterDeep.isSparse && !info._filterDeep.excluded) { + condense(info.children); + } + } + if (resIsArray) { + condense(res); + } } - - artifact(id) { - - Assert(id !== undefined, 'Artifact cannot be undefined'); - Assert(!this._cache, 'Cannot set an artifact with a rule cache'); - - return this.$_setFlag('artifact', id); + if (resIsArray && !res.length && !eachDeepOptions.includeRoot) { + return null; } - cast(to) { - - Assert(to === false || typeof to === 'string', 'Invalid to value'); - Assert(to === false || this._definition.cast[to], 'Type', this.type, 'does not support casting to', to); + return res; + } + return filterDeep; - return this.$_setFlag('cast', to === false ? undefined : to); + function takeResultParent(context, res) { + if (context.parent.info.children) { + return context.parent.info.children; } - - default(value, options) { - - return this._default('default', value, options); + if (!context.parent.info._filterDeep) { + context.parent.info._filterDeep = {}; } - - description(desc) { - - Assert(desc && typeof desc === 'string', 'Description must be a non-empty string'); - - return this.$_setFlag('description', desc); + var parent = context.parent.info._filterDeep.res; + if (parent === undefined) { + //if (!context.parent.parent) { + parent = context.parent.info._filterDeep.res = res; + // } else { + // parent = context.parent.info._filterDeep.res = Array.isArray(context.parent.value) + // ? [] + // : {}; + // } } - - empty(schema) { - - const obj = this.clone(); - - if (schema !== undefined) { - schema = obj.$_compile(schema, { override: false }); + if (context._item.childrenPath) { + var oParent = context.parent.value; + for (var i = 0; i < context._item.childrenPath.length; i++) { + var childKey = context._item.childrenPath[i]; + oParent = oParent[childKey]; + if (!parent[childKey]) { + parent[childKey] = Array.isArray(oParent) ? [] : {}; } - - return obj.$_setFlag('empty', schema, { clone: false }); - } - - error(err) { - - Assert(err, 'Missing error'); - Assert(err instanceof Error || typeof err === 'function', 'Must provide a valid Error object or a function'); - - return this.$_setFlag('error', err); + parent = parent[childKey]; + } } + context.parent.info.children = parent; + return parent; + } +} - example(example, options = {}) { +module.exports = getFilterDeep; - Assert(example !== undefined, 'Missing example'); - Common.assertOptions(options, ['override']); - return this._inner('examples', example, { single: true, override: options.override }); - } +/***/ }), - external(method, description) { +/***/ 14850: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof method === 'object') { - Assert(!description, 'Cannot combine options with description'); - description = method.description; - method = method.method; - } +"use strict"; - Assert(typeof method === 'function', 'Method must be a function'); - Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); - return this._inner('externals', { method, description }, { single: true }); - } +var getEachDeep = __nccwpck_require__(47016); - failover(value, options) { +function getFindDeep(_) { + var eachDeep = getEachDeep(_); - return this._default('failover', value, options); + function findDeep(obj, predicate, options) { + predicate = _.iteratee(predicate); + if (!options) { + options = {}; + } else { + options = _.cloneDeep(options); + if (options.leafsOnly !== undefined) { + options.leavesOnly = options.leafsOnly; + } } - forbidden() { + options = _.merge( + { + checkCircular: false, + leavesOnly: options.childrenPath === undefined, + pathFormat: 'string', + }, + options + ); - return this.presence('forbidden'); - } + var eachDeepOptions = { + pathFormat: options.pathFormat, + checkCircular: options.checkCircular, + ownPropertiesOnly: options.ownPropertiesOnly, + childrenPath: options.childrenPath, + includeRoot: options.includeRoot, + rootIsChildren: options.rootIsChildren, + callbackAfterIterate: false, + leavesOnly: options.leavesOnly, + }; - id(id) { + var res; - if (!id) { - return this.$_setFlag('id', undefined); + eachDeep( + obj, + function (value, key, parent, context) { + if (predicate(value, key, parent, context)) { + res = { value: value, key: key, parent: parent, context: context }; + return context['break'](); } + }, + eachDeepOptions + ); + return res; + } + return findDeep; +} - Assert(typeof id === 'string', 'id must be a non-empty string'); - Assert(/^[^\.]+$/.test(id), 'id cannot contain period character'); - - return this.$_setFlag('id', id); - } - - invalid(...values) { - - return this._values(values, '_invalids'); - } - - label(name) { +module.exports = getFindDeep; - Assert(name && typeof name === 'string', 'Label name must be a non-empty string'); - return this.$_setFlag('label', name); - } +/***/ }), - meta(meta) { +/***/ 73970: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Assert(meta !== undefined, 'Meta cannot be undefined'); +"use strict"; - return this._inner('metas', meta, { single: true }); - } - note(...notes) { +var getFindDeep = __nccwpck_require__(14850); - Assert(notes.length, 'Missing notes'); - for (const note of notes) { - Assert(note && typeof note === 'string', 'Notes must be non-empty strings'); - } +function getFindPathDeep(_) { + var findDeep = getFindDeep(_); + function findPathDeep(obj, predicate, options) { + var res = findDeep(obj, predicate, options); + return res && res.context.path; + } + return findPathDeep; +} - return this._inner('notes', notes); - } +module.exports = getFindPathDeep; - only(mode = true) { - Assert(typeof mode === 'boolean', 'Invalid mode:', mode); +/***/ }), - return this.$_setFlag('only', mode); - } +/***/ 84392: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - optional() { +"use strict"; - return this.presence('optional'); - } - prefs(prefs) { +var getFindDeep = __nccwpck_require__(14850); - Assert(prefs, 'Missing preferences'); - Assert(prefs.context === undefined, 'Cannot override context'); - Assert(prefs.externals === undefined, 'Cannot override externals'); - Assert(prefs.warnings === undefined, 'Cannot override warnings'); - Assert(prefs.debug === undefined, 'Cannot override debug'); +function getFindValueDeep(_) { + var findDeep = getFindDeep(_); + function findValueDeep(obj, predicate, options) { + var res = findDeep(obj, predicate, options); + return res && res.value; + } + return findValueDeep; +} - Common.checkPreferences(prefs); +module.exports = getFindValueDeep; - const obj = this.clone(); - obj._preferences = Common.preferences(obj._preferences, prefs); - return obj; - } - presence(mode) { +/***/ }), - Assert(['optional', 'required', 'forbidden'].includes(mode), 'Unknown presence mode', mode); +/***/ 47164: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this.$_setFlag('presence', mode); - } +"use strict"; - raw(enabled = true) { - return this.$_setFlag('result', enabled ? 'raw' : undefined); - } +var getEachDeep = __nccwpck_require__(47016); - result(mode) { +function getForEachDeep(_) { + return getEachDeep(_); +} - Assert(['raw', 'strip'].includes(mode), 'Unknown result mode', mode); +module.exports = getForEachDeep; - return this.$_setFlag('result', mode); - } - required() { +/***/ }), - return this.presence('required'); - } +/***/ 13953: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - strict(enabled) { +"use strict"; - const obj = this.clone(); - const convert = enabled === undefined ? false : !enabled; - obj._preferences = Common.preferences(obj._preferences, { convert }); - return obj; - } +var getEachDeep = __nccwpck_require__(47016); - strip(enabled = true) { +function getIndex(_) { + var eachDeep = getEachDeep(_); - return this.$_setFlag('result', enabled ? 'strip' : undefined); + function index(obj, options) { + options = _.merge( + { + checkCircular: false, + includeCircularPath: true, + leavesOnly: !options || options.childrenPath === undefined, + }, + options || {} + ); + if (options && options.leafsOnly !== undefined) { + options.leavesOnly = options.leafsOnly; } - - tag(...tags) { - - Assert(tags.length, 'Missing tags'); - for (const tag of tags) { - Assert(tag && typeof tag === 'string', 'Tags must be non-empty strings'); + var eachDeepOptions = { + pathFormat: 'string', + checkCircular: options.checkCircular, + ownPropertiesOnly: options.ownPropertiesOnly, + includeRoot: options.includeRoot, + childrenPath: options.childrenPath, + rootIsChildren: options.rootIsChildren, + leavesOnly: options.leavesOnly, + }; + var res = {}; + eachDeep( + obj, + function (value, key, parent, context) { + if (!context.isCircular || options.includeCircularPath) { + if (context.path !== undefined) { + res[context.path] = value; + } } + }, + eachDeepOptions + ); + return res; + } + return index; +} - return this._inner('tags', tags); - } - - unit(name) { +module.exports = getIndex; - Assert(name && typeof name === 'string', 'Unit name must be a non-empty string'); - return this.$_setFlag('unit', name); - } +/***/ }), - valid(...values) { +/***/ 91152: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Common.verifyFlat(values, 'valid'); +"use strict"; - const obj = this.allow(...values); - obj.$_setFlag('only', !!obj._valids, { clone: false }); - return obj; - } - when(condition, options) { +var getPaths = __nccwpck_require__(49633); - const obj = this.clone(); +function getKeysDeep(_) { + return getPaths(_); +} - if (!obj.$_terms.whens) { - obj.$_terms.whens = []; - } +module.exports = getKeysDeep; - const when = Compile.when(obj, condition, options); - if (!['any', 'link'].includes(obj.type)) { - const conditions = when.is ? [when] : when.switch; - for (const item of conditions) { - Assert(!item.then || item.then.type === 'any' || item.then.type === obj.type, 'Cannot combine', obj.type, 'with', item.then && item.then.type); - Assert(!item.otherwise || item.otherwise.type === 'any' || item.otherwise.type === obj.type, 'Cannot combine', obj.type, 'with', item.otherwise && item.otherwise.type); - } - } +/***/ }), - obj.$_terms.whens.push(when); - return obj.$_mutateRebuild(); - } +/***/ 86139: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Helpers +"use strict"; - cache(cache) { - Assert(!this._inRuleset(), 'Cannot set caching inside a ruleset'); - Assert(!this._cache, 'Cannot override schema cache'); - Assert(this._flags.artifact === undefined, 'Cannot cache a rule with an artifact'); +var getReduceDeep = __nccwpck_require__(97878); - const obj = this.clone(); - obj._cache = cache || Cache.provider.provision(); - obj.$_temp.ruleset = false; - return obj; - } +function getMapDeep(_) { + var reduceDeep = getReduceDeep(_); - clone() { + function mapDeep(obj, iteratee, options) { + iteratee = _.iteratee(iteratee); + return reduceDeep( + obj, + function (acc, value, key, parentValue, context) { + acc.push(iteratee(value, key, parentValue, context)); + return acc; + }, + [], + options + ); + } + return mapDeep; +} - const obj = Object.create(Object.getPrototypeOf(this)); - return this._assign(obj); - } +module.exports = getMapDeep; - concat(source) { - Assert(Common.isSchema(source), 'Invalid schema object'); - Assert(this.type === 'any' || source.type === 'any' || source.type === this.type, 'Cannot merge type', this.type, 'with another type:', source.type); - Assert(!this._inRuleset(), 'Cannot concatenate onto a schema with open ruleset'); - Assert(!source._inRuleset(), 'Cannot concatenate a schema with open ruleset'); +/***/ }), - let obj = this.clone(); +/***/ 28192: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.type === 'any' && - source.type !== 'any') { +"use strict"; - // Change obj to match source type - const tmpObj = source.clone(); - for (const key of Object.keys(obj)) { - if (key !== 'type') { - tmpObj[key] = obj[key]; - } - } +var getPathToString = __nccwpck_require__(69937); +var getEachDeep = __nccwpck_require__(47016); - obj = tmpObj; - } +function getMapKeysDeep(_) { + var eachDeep = getEachDeep(_); + var pathToString = getPathToString(_); + function mapKeysDeep(obj, iteratee, options) { + if ( options === void 0 ) options = {}; - obj._ids.concat(source._ids); - obj._refs.register(source, Ref.toSibling); + iteratee = _.iteratee(iteratee); + options.cloneDeep = options.cloneDeep || _.cloneDeep; + options.callbackAfterIterate = false; + var newPaths = []; - obj._preferences = obj._preferences ? Common.preferences(obj._preferences, source._preferences) : source._preferences; - obj._valids = Values.merge(obj._valids, source._valids, source._invalids); - obj._invalids = Values.merge(obj._invalids, source._invalids, source._valids); + eachDeep( + obj, + function (value, key, parent, context) { + if (key === undefined) { + return; + } + var newKey = iteratee(value, key, parent, context) + ''; + if (newKey === key) { + return; + } + var oldPath = context.path; + var oldPathStr = + options.pathFormat === 'array' ? JSON.stringify(oldPath) : oldPath; + var newPath = + options.pathFormat === 'array' + ? (context.parent.path || []).concat( (context.childrenPath || []), + [newKey] ) + : pathToString([newKey], context.parent.path, context.childrenPath); + var newPathStr = + options.pathFormat === 'array' ? JSON.stringify(newPath) : newPath; + if (!newPaths[context.depth - 1]) { + newPaths[context.depth - 1] = []; + } + newPaths[context.depth - 1].push({ + oldPath: oldPath, + oldPathStr: oldPathStr, + newPath: newPath, + newPathStr: newPathStr, + }); + }, + options + ); + var res = options.cloneDeep(obj); - // Remove unique rules present in source + var d = newPaths.length; + var loop = function () { + if (!newPaths[d]) { + return; + } + var overwritten = {}; + newPaths[d].forEach(function (ref) { + var oldPath = ref.oldPath; + var oldPathStr = ref.oldPathStr; + var newPath = ref.newPath; + var newPathStr = ref.newPathStr; - for (const name of source._singleRules.keys()) { - if (obj._singleRules.has(name)) { - obj._rules = obj._rules.filter((target) => target.keep || target.name !== name); - obj._singleRules.delete(name); - } + var value; + if (Object.prototype.hasOwnProperty.call(overwritten, oldPathStr)) { + value = overwritten[oldPathStr]; + delete overwritten[oldPathStr]; + } else { + value = _.get(res, oldPath); + if (value === undefined && !_.has(res, oldPath)) { + return; + } + _.unset(res, oldPath); + } + if ( + _.has(res, newPath) && + !Object.prototype.hasOwnProperty.call(overwritten, newPathStr) + ) { + overwritten[newPathStr] = _.get(res, newPath); } + _.set(res, newPath, value); + }); + }; - // Rules + while (d--) loop(); + return res; + } + return mapKeysDeep; +} - for (const test of source._rules) { - if (!source._definition.rules[test.method].multi) { - obj._singleRules.set(test.name, test); - } +module.exports = getMapKeysDeep; - obj._rules.push(test); - } - // Flags +/***/ }), - if (obj._flags.empty && - source._flags.empty) { +/***/ 49743: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - obj._flags.empty = obj._flags.empty.concat(source._flags.empty); - const flags = Object.assign({}, source._flags); - delete flags.empty; - Merge(obj._flags, flags); - } - else if (source._flags.empty) { - obj._flags.empty = source._flags.empty; - const flags = Object.assign({}, source._flags); - delete flags.empty; - Merge(obj._flags, flags); - } - else { - Merge(obj._flags, source._flags); - } +"use strict"; - // Terms - for (const key in source.$_terms) { - const terms = source.$_terms[key]; - if (!terms) { - if (!obj.$_terms[key]) { - obj.$_terms[key] = terms; - } +var getEachDeep = __nccwpck_require__(47016); - continue; - } +function getMapValuesDeep(_) { + var eachDeep = getEachDeep(_); - if (!obj.$_terms[key]) { - obj.$_terms[key] = terms.slice(); - continue; - } + function mapValuesDeep(obj, iteratee, options) { + iteratee = _.iteratee(iteratee); + var res = Array.isArray(obj) ? [] : _.isObject(obj) ? {} : _.clone(obj); + var skipChildren; - obj.$_terms[key] = obj.$_terms[key].concat(terms); + eachDeep( + obj, + function (value, key, parent, context) { + // if (!context.skipChildren) { + context.skipChildren = function (skip) { + skipChildren = skip; + }; + // } + skipChildren = undefined; + var r = iteratee(value, key, parent, context); + if (!context.isLeaf && skipChildren === undefined) { + skipChildren = + value !== r && Array.isArray(value) != Array.isArray(r); } - - // Tracing - - if (this.$_root._tracer) { - this.$_root._tracer._combine(obj, [this, source]); + if (context.path !== undefined) { + _.set(res, context.path, r); + } else { + res = r; + } + if (skipChildren) { + return false; } + }, + options + ); - // Rebuild + return res; + } + return mapValuesDeep; +} - return obj.$_mutateRebuild(); - } +module.exports = getMapValuesDeep; - extend(options) { - Assert(!options.base, 'Cannot extend type with another base'); +/***/ }), - return Extend.type(this, options); - } +/***/ 81192: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - extract(path) { +"use strict"; - path = Array.isArray(path) ? path : path.split('.'); - return this._ids.reach(path); - } - fork(paths, adjuster) { +var getFilterDeep = __nccwpck_require__(79175); +var getPathMatches = __nccwpck_require__(8127); - Assert(!this._inRuleset(), 'Cannot fork inside a ruleset'); +function getOmitDeep(_) { + var pathMatches = getPathMatches(_); + var filterDeep = getFilterDeep(_); - let obj = this; // eslint-disable-line consistent-this - for (let path of [].concat(paths)) { - path = Array.isArray(path) ? path : path.split('.'); - obj = obj._ids.fork(path, adjuster, obj); - } + function omitDeep(obj, paths, options) { + options = _.merge( + { + invert: false, + }, + options || {} + ); + var isOmit = !options.invert; + options = _.merge( + { + onMatch: { + cloneDeep: false, + skipChildren: false, + keepIfEmpty: !isOmit, + }, + onNotMatch: { + cloneDeep: false, + skipChildren: false, + keepIfEmpty: isOmit, + }, + }, + options + ); + options.leavesOnly = false; + options.childrenPath = undefined; + options.includeRoot = undefined; + options.pathFormat = 'array'; + options.onTrue = options.invert ? options.onMatch : options.onNotMatch; + options.onFalse = options.invert ? options.onNotMatch : options.onMatch; - obj.$_temp.ruleset = false; - return obj; - } + var test = function (value, key, parent, context) { + if (pathMatches(context.path, paths) !== false) { + return options.invert; + } else { + return !options.invert; + } + }; + return filterDeep(obj, test, options); + } + return omitDeep; +} - rule(options) { +module.exports = getOmitDeep; - const def = this._definition; - Common.assertOptions(options, Object.keys(def.modifiers)); - Assert(this.$_temp.ruleset !== false, 'Cannot apply rules to empty ruleset or the last rule added does not support rule properties'); - const start = this.$_temp.ruleset === null ? this._rules.length - 1 : this.$_temp.ruleset; - Assert(start >= 0 && start < this._rules.length, 'Cannot apply rules to empty ruleset'); +/***/ }), - const obj = this.clone(); +/***/ 8127: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (let i = start; i < obj._rules.length; ++i) { - const original = obj._rules[i]; - const rule = Clone(original); +"use strict"; - for (const name in options) { - def.modifiers[name](rule, options[name]); - Assert(rule.name === original.name, 'Cannot change rule name'); - } - obj._rules[i] = rule; +var getPathToString = __nccwpck_require__(69937); - if (obj._singleRules.get(rule.name) === original) { - obj._singleRules.set(rule.name, rule); - } +function getPathMatches(_) { + var pathToString = getPathToString(_); + function pathMatches(path, paths) { + var pathString; + var pathArray; + if (_.isString(path)) { + pathString = path; + } else { + pathArray = path; + } + if (!Array.isArray(paths)) { + paths = [paths]; + } else { + paths = _.cloneDeep(paths); + } + for (var i = 0; i < paths.length; i++) { + if (_.isString(paths[i])) { + paths[i] = _.toPath(paths[i]); + } + if (Array.isArray(paths[i])) { + if (pathArray === undefined) { + pathArray = _.toPath(pathString); } - - obj.$_temp.ruleset = false; - return obj.$_mutateRebuild(); + if ( + pathArray.length >= paths[i].length && + _.isEqual(_.takeRight(pathArray, paths[i].length), paths[i]) + ) { + // console.log('path matched'); + return paths[i]; + } + } else if (paths[i] instanceof RegExp) { + if (pathString === undefined) { + pathString = pathToString(path); + } + if (paths[i].test(pathString)) { + // console.log('regex matched', paths[i]); + return paths[i]; + } + } else { + throw new Error( + 'To match path use only string/regex or array of them.' + ); + } } + // console.log('matched nothing'); + return false; + } + return pathMatches; +} - get ruleset() { +getPathMatches.notChainable = true; - Assert(!this._inRuleset(), 'Cannot start a new ruleset without closing the previous one'); +module.exports = getPathMatches; - const obj = this.clone(); - obj.$_temp.ruleset = obj._rules.length; - return obj; - } - get $() { +/***/ }), - return this.ruleset; - } +/***/ 69937: +/***/ ((module) => { - tailor(targets) { +"use strict"; - targets = [].concat(targets); - Assert(!this._inRuleset(), 'Cannot tailor inside a ruleset'); +var rxArrIndex = /\D/; +var rxVarName = /^[a-zA-Z_$]+([\w_$]*)$/; +var rxQuot = /"/g; - let obj = this; // eslint-disable-line consistent-this +function joinPaths() { + var paths = [], len = arguments.length; + while ( len-- ) paths[ len ] = arguments[ len ]; - if (this.$_terms.alterations) { - for (const { target, adjuster } of this.$_terms.alterations) { - if (targets.includes(target)) { - obj = adjuster(obj); - Assert(Common.isSchema(obj), 'Alteration adjuster for', target, 'failed to return a schema object'); - } - } - } + return paths.reduce( + function (acc, p) { return acc ? (!p || p.startsWith('[') ? ("" + acc + p) : (acc + "." + p)) : p; }, + '' + ); +} - obj = obj.$_modify({ each: (item) => item.tailor(targets), ref: false }); - obj.$_temp.ruleset = false; - return obj.$_mutateRebuild(); - } +function getPathToString(_) { + function pathToString(path) { + var prefixes = [], len = arguments.length - 1; + while ( len-- > 0 ) prefixes[ len ] = arguments[ len + 1 ]; - tracer() { + prefixes = prefixes.filter(function (p) { return p !== undefined; }); + if (_.isString(path)) { return joinPaths.apply(void 0, prefixes.concat( [path] )); } + if (!Array.isArray(path)) { return undefined; } + prefixes = joinPaths.apply(void 0, prefixes); + return path.reduce(function (acc, value) { + var type = typeof value; + if (type === 'number') { + if (value < 0 || value % 1 !== 0) { + return (acc + "[\"" + value + "\"]"); + } else { + return (acc + "[" + value + "]"); + } + } else if (type !== 'string') { + return (acc + "[\"" + value + "\"]"); + } else if (!value) { + return (acc + "[\"\"]"); + } + if (!rxArrIndex.test(value)) { + return (acc + "[" + value + "]"); + } + if (rxVarName.test(value)) { + if (acc) { + return (acc + "." + value); + } else { + return ("" + acc + value); + } + } + return (acc + "[\"" + (value.replace(rxQuot, '\\"')) + "\"]"); + }, prefixes); + } + return pathToString; +} - return Trace.location ? Trace.location(this) : this; // $lab:coverage:ignore$ - } +getPathToString.notChainable = true; - validate(value, options) { +module.exports = getPathToString; - return Validator.entry(value, this, options); - } - validateAsync(value, options) { +/***/ }), - return Validator.entryAsync(value, this, options); - } +/***/ 49633: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Extensions +"use strict"; - $_addRule(options) { - // Normalize rule +var getEachDeep = __nccwpck_require__(47016); - if (typeof options === 'string') { - options = { name: options }; +function getPaths(_) { + var eachDeep = getEachDeep(_); + function paths(obj, options) { + if (options && options.leafsOnly !== undefined) { + options.leavesOnly = options.leafsOnly; + } + options = _.merge( + { + checkCircular: false, + includeCircularPath: true, + leavesOnly: !options || options.childrenPath === undefined, + pathFormat: 'string', + }, + options || {} + ); + var eachDeepOptions = { + pathFormat: options.pathFormat, + checkCircular: options.checkCircular, + ownPropertiesOnly: options.ownPropertiesOnly, + includeRoot: options.includeRoot, + childrenPath: options.childrenPath, + rootIsChildren: options.rootIsChildren, + leavesOnly: options.leavesOnly, + }; + var res = []; + eachDeep( + obj, + function (value, key, parent, context) { + if (!context.isCircular || options.includeCircularPath) { + if (context.path !== undefined) { + res.push(context.path); + } } + }, + eachDeepOptions + ); + return res; + } + return paths; +} - Assert(options && typeof options === 'object', 'Invalid options'); - Assert(options.name && typeof options.name === 'string', 'Invalid rule name'); +module.exports = getPaths; - for (const key in options) { - Assert(key[0] !== '_', 'Cannot set private rule properties'); - } - const rule = Object.assign({}, options); // Shallow cloned - rule._resolve = []; - rule.method = rule.method || rule.name; +/***/ }), - const definition = this._definition.rules[rule.method]; - const args = rule.args; +/***/ 64541: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Assert(definition, 'Unknown rule', rule.method); +"use strict"; - // Args - const obj = this.clone(); +var getOmitDeep = __nccwpck_require__(81192); - if (args) { - Assert(Object.keys(args).length === 1 || Object.keys(args).length === this._definition.rules[rule.name].args.length, 'Invalid rule definition for', this.type, rule.name); +function getPickDeep(_) { + var omitDeep = getOmitDeep(_); + function pickDeep(obj, paths, options) { + options = _.merge( + { + invert: false, + }, + options || {} + ); + options.invert = true; + return omitDeep(obj, paths, options); + } + return pickDeep; +} - for (const key in args) { - let arg = args[key]; +module.exports = getPickDeep; - if (definition.argsByName) { - const resolver = definition.argsByName.get(key); - if (resolver.ref && - Common.isResolvable(arg)) { +/***/ }), - rule._resolve.push(key); - obj.$_mutateRegister(arg); - } - else { - if (resolver.normalize) { - arg = resolver.normalize(arg); - args[key] = arg; - } +/***/ 97878: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (resolver.assert) { - const error = Common.validateArg(arg, key, resolver); - Assert(!error, error, 'or reference'); - } - } - } +"use strict"; - if (arg === undefined) { - delete args[key]; - continue; - } - args[key] = arg; - } - } +var getEachDeep = __nccwpck_require__(47016); - // Unique rules +function getReduceDeep(_) { + var eachDeep = getEachDeep(_); - if (!definition.multi) { - obj._ruleRemove(rule.name, { clone: false }); - obj._singleRules.set(rule.name, rule); + function reduceDeep(obj, iteratee, accumulator, options) { + var accumulatorInited = accumulator !== undefined; + eachDeep( + obj, + function (value, key, parent, context) { + if (!accumulatorInited) { + accumulator = value; + accumulatorInited = true; + } else { + accumulator = iteratee(accumulator, value, key, parent, context); } + }, + options + ); + return accumulator; + } + return reduceDeep; +} + +module.exports = getReduceDeep; - if (obj.$_temp.ruleset === false) { - obj.$_temp.ruleset = null; - } - if (definition.priority) { - obj._rules.unshift(rule); - } - else { - obj._rules.push(rule); - } +/***/ }), - return obj; - } +/***/ 34949: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - $_compile(schema, options) { +"use strict"; - return Compile.schema(this.$_root, schema, options); - } - $_createError(code, value, local, state, prefs, options = {}) { +var getFindDeep = __nccwpck_require__(14850); - const flags = options.flags !== false ? this._flags : {}; - const messages = options.messages ? Messages.merge(this._definition.messages, options.messages) : this._definition.messages; - return new Errors.Report(code, value, local, flags, messages, state, prefs); - } +function getSomeDeep(_) { + var findDeep = getFindDeep(_); + function someDeep(obj, predicate, options) { + return !!findDeep(obj, predicate, options); + } + return someDeep; +} - $_getFlag(name) { +module.exports = getSomeDeep; - return this._flags[name]; - } - $_getRule(name) { +/***/ }), - return this._singleRules.get(name); - } +/***/ 55267: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - $_mapLabels(path) { +"use strict"; - path = Array.isArray(path) ? path : path.split('.'); - return this._ids.labels(path); - } - $_match(value, state, prefs, overrides) { +var getPathToString = __nccwpck_require__(69937); +var isObject = __nccwpck_require__(86564); - prefs = Object.assign({}, prefs); // Shallow cloned - prefs.abortEarly = true; - prefs._externals = false; +var rxVarName = /^[a-zA-Z_$]+([\w_$]*)$/; +var rxQuot = /"/g; +var has = Object.prototype.hasOwnProperty; - state.snapshot(); - const result = !Validator.validate(value, this, state, prefs, overrides).errors; - state.restore(); +function getIterate(_) { + var pathToString = getPathToString(_); - return result; - } + function iterate(item) { + var options = item.options; + var obj = item.obj; + var callback = item.callback; + options.pathFormatArray = options.pathFormat == 'array'; + item.depth = 0; - $_modify(options) { + var broken = false; + var breakIt = function () { + broken = true; + return false; + }; - Common.assertOptions(options, ['each', 'once', 'ref', 'schema']); - return Modify.schema(this, options) || this; - } + while (item) { + if (broken) { break; } + if (!item.inited) { + item.inited = true; + item.info = describeValue(item.value, options.ownPropertiesOnly); - $_mutateRebuild() { + if (options.checkCircular) { + item.circularParentIndex = -1; + item.circularParent = null; + item.isCircular = false; + if (item.info.isObject && !item.info.isEmpty) { + var parent = item.parent; + while (parent) { + if (parent.value === item.value) { + item.isCircular = true; + item.circularParent = parent; + item.circularParentIndex = item.depth - parent.depth - 1; + break; + } + parent = parent.parent; + } + } + } - Assert(!this._inRuleset(), 'Cannot add this rule inside a ruleset'); + item.children = []; + if (options.childrenPath) { + options.childrenPath.forEach(function (cp, i) { + var children = _.get(item.value, cp); + var info = describeValue(children, options.ownPropertiesOnly); + if (!info.isEmpty) { + item.children.push([ + cp, + options.strChildrenPath[i], + children, + info ]); + } + }); + } - this._refs.reset(); - this._ids.reset(); + item.isLeaf = + item.isCircular || + (options.childrenPath !== undefined && !item.children.length) || + !item.info.isObject || + item.info.isEmpty; - const each = (item, { source, name, path, key }) => { + item.needCallback = + (item.depth || options.includeRoot) && + (!options.leavesOnly || item.isLeaf); - const family = this._definition[source][name] && this._definition[source][name].register; - if (family !== false) { - this.$_mutateRegister(item, { family, key }); + if (item.needCallback) { + var contextReader = new ContextReader(obj, options, breakIt); + contextReader.setItem(item, false); + try { + item.res = callback( + item.value, + item.key, + item.parent && item.parent.value, + contextReader + ); + } catch (err) { + if (err.message) { + err.message += + '\ncallback failed before deep iterate at:\n' + + pathToString(item.path); } - }; - this.$_modify({ each }); + throw err; + } + } - if (this._definition.rebuild) { - this._definition.rebuild(this); + if (broken) { + break; } - this.$_temp.ruleset = false; - return this; - } + if (item.res !== false) { + if (!broken && !item.isCircular && item.info.isObject) { + if ( + options.childrenPath !== undefined && + (item.depth || !options.rootIsChildren) + ) { + item.childrenItems = []; + if (item.children.length) { + item.children.forEach(function (ref) { + var cp = ref[0]; + var scp = ref[1]; + var children = ref[2]; + var info = ref[3]; - $_mutateRegister(schema, { family, key } = {}) { + item.childrenItems = ( item.childrenItems ).concat( (info.isArray + ? getElements(item, children, options, cp, scp) + : getOwnChildren(item, children, options, cp, scp)) ); + }); + } + } else { + item.childrenItems = item.info.isArray + ? getElements(item, item.value, options, [], '') + : getOwnChildren(item, item.value, options, [], ''); + } + } + } - this._refs.register(schema, family); - this._ids.register(schema, { key }); + item.currentChildIndex = -1; + } + if ( + item.childrenItems && + item.currentChildIndex < item.childrenItems.length - 1 + ) { + item.currentChildIndex++; + item.childrenItems[item.currentChildIndex].parentItem = item; + item = item.childrenItems[item.currentChildIndex]; + continue; + } + + if (item.needCallback && options.callbackAfterIterate) { + var contextReader$1 = new ContextReader(obj, options, breakIt); + contextReader$1.setItem(item, true); + + try { + callback( + item.value, + item.key, + item.parent && item.parent.value, + contextReader$1 + ); + } catch (err) { + if (err.message) { + err.message += + '\ncallback failed after deep iterate at:\n' + + pathToString(item.path); + } + + throw err; + } + } + item = item.parentItem; } + } - $_property(name) { + return iterate; - return this._definition.properties[name]; + function getElements(item, children, options, childrenPath, strChildrenPath) { + var strChildPathPrefix; + if (!options.pathFormatArray) { + strChildPathPrefix = item.strPath || ''; + + if ( + strChildrenPath && + strChildPathPrefix && + !strChildrenPath.startsWith('[') + ) { + strChildPathPrefix += '.'; + } + strChildPathPrefix += strChildrenPath || ''; + } + var res = []; + for (var i = 0; i < children.length; i++) { + var val = children[i]; + if (val === undefined && !(i in children)) { + continue; + } + var strChildPath = (void 0); + var pathFormatString = !options.pathFormatArray; + if (pathFormatString) { + strChildPath = strChildPathPrefix + "[" + i + "]"; + } + res.push({ + value: val, + key: i + '', + path: (item.path || []).concat( childrenPath, [i + '']), + strPath: strChildPath, + depth: item.depth + 1, + parent: { + value: item.value, + key: item.key, + path: pathFormatString ? item.strPath : item.path, + parent: item.parent, + depth: item.depth, + info: item.info, + }, + childrenPath: (childrenPath.length && childrenPath) || undefined, + strChildrenPath: strChildrenPath || undefined, + }); } + return res; + } - $_reach(path) { + function getOwnChildren( + item, + children, + options, + childrenPath, + strChildrenPath + ) { + var strChildPathPrefix; + if (!options.pathFormatArray) { + strChildPathPrefix = item.strPath || ''; - return this._ids.reach(path); + if ( + strChildrenPath && + strChildPathPrefix && + !strChildrenPath.startsWith('[') + ) { + strChildPathPrefix += '.'; + } + strChildPathPrefix += strChildrenPath || ''; } + var res = []; + var pathFormatString = !options.pathFormatArray; + for (var childKey in children) { + if (options.ownPropertiesOnly && !has.call(children, childKey)) { + continue; + } - $_rootReferences() { + var strChildPath = (void 0); + if (pathFormatString) { + if (rxVarName.test(childKey)) { + if (strChildPathPrefix) { + strChildPath = strChildPathPrefix + "." + childKey; + } else { + strChildPath = "" + childKey; + } + } else { + strChildPath = strChildPathPrefix + "[\"" + (childKey.replace( + rxQuot, + '\\"' + )) + "\"]"; + } + } - return this._refs.roots(); + res.push({ + value: children[childKey], + key: childKey, + path: (item.path || []).concat( childrenPath, [childKey]), + strPath: strChildPath, + depth: item.depth + 1, + parent: { + value: item.value, + key: item.key, + path: pathFormatString ? item.strPath : item.path, + parent: item.parent, + depth: item.depth, + info: item.info, + }, + childrenPath: (childrenPath.length && childrenPath) || undefined, + strChildrenPath: strChildrenPath || undefined, + }); } - $_setFlag(name, value, options = {}) { + return res; + } +} - Assert(name[0] === '_' || !this._inRuleset(), 'Cannot set flag inside a ruleset'); +var ContextReader = function ContextReader(obj, options, breakIt) { + this.obj = obj; + this._options = options; + this['break'] = breakIt; +}; - const flag = this._definition.flags[name] || {}; - if (DeepEqual(value, flag.default)) { - value = undefined; - } +var prototypeAccessors = { path: { configurable: true },parent: { configurable: true },parents: { configurable: true },depth: { configurable: true },isLeaf: { configurable: true },isCircular: { configurable: true },circularParentIndex: { configurable: true },circularParent: { configurable: true },childrenPath: { configurable: true },info: { configurable: true } }; +ContextReader.prototype.setItem = function setItem (item, afterIterate) { + this._item = item; + this.afterIterate = afterIterate; +}; +prototypeAccessors.path.get = function () { + return this._options.pathFormatArray ? this._item.path : this._item.strPath; +}; - if (DeepEqual(value, this._flags[name])) { - return this; - } +prototypeAccessors.parent.get = function () { + return this._item.parent; +}; - const obj = options.clone !== false ? this.clone() : this; +prototypeAccessors.parents.get = function () { + if (!this._item._parents) { + this._item._parents = []; + var curParent = this._item.parent; + while (curParent) { + this._item._parents[curParent.depth] = curParent; + curParent = curParent.parent; + } + } + return this._item._parents; +}; +prototypeAccessors.depth.get = function () { + return this._item.depth; +}; - if (value !== undefined) { - obj._flags[name] = value; - obj.$_mutateRegister(value); - } - else { - delete obj._flags[name]; - } +prototypeAccessors.isLeaf.get = function () { + return this._item.isLeaf; +}; - if (name[0] !== '_') { - obj.$_temp.ruleset = false; - } +prototypeAccessors.isCircular.get = function () { + return this._item.isCircular; +}; - return obj; - } +prototypeAccessors.circularParentIndex.get = function () { + return this._item.circularParentIndex; +}; - $_parent(method, ...args) { +prototypeAccessors.circularParent.get = function () { + return this._item.circularParent; +}; - return this[method][Common.symbols.parent].call(this, ...args); - } +prototypeAccessors.childrenPath.get = function () { + return ( + (this._options.childrenPath !== undefined && + (this._options.pathFormatArray + ? this._item.childrenPath + : this._item.strChildrenPath)) || + undefined + ); +}; - $_validate(value, state, prefs) { +prototypeAccessors.info.get = function () { + return this._item.info; +}; - return Validator.validate(value, this, state, prefs); - } +Object.defineProperties( ContextReader.prototype, prototypeAccessors ); - // Internals +function isObjectEmpty(value, ownPropertiesOnly) { + for (var key in value) { + if (!ownPropertiesOnly || has.call(value, key)) { + return false; + } + } + return true; +} - _assign(target) { +function describeValue(value, ownPropertiesOnly) { + var res = { isObject: isObject(value) }; + res.isArray = res.isObject && Array.isArray(value); + res.isEmpty = res.isArray + ? !value.length + : res.isObject + ? isObjectEmpty(value, ownPropertiesOnly) + : true; - target.type = this.type; + return res; +} - target.$_root = this.$_root; +module.exports = getIterate; - target.$_temp = Object.assign({}, this.$_temp); - target.$_temp.whens = {}; - target._ids = this._ids.clone(); - target._preferences = this._preferences; - target._valids = this._valids && this._valids.clone(); - target._invalids = this._invalids && this._invalids.clone(); - target._rules = this._rules.slice(); - target._singleRules = Clone(this._singleRules, { shallow: true }); - target._refs = this._refs.clone(); - target._flags = Object.assign({}, this._flags); - target._cache = null; +/***/ }), - target.$_terms = {}; - for (const key in this.$_terms) { - target.$_terms[key] = this.$_terms[key] ? this.$_terms[key].slice() : null; - } +/***/ 22514: +/***/ ((module) => { - // Backwards compatibility +"use strict"; - target.$_super = {}; - for (const override in this.$_super) { - target.$_super[override] = this._super[override].bind(target); - } - return target; +function getMixOrPatchIn(_) { + function mixOrPatchIn(name, method, chain) { + if (!_[name]) { + if (_.mixin) { + var patch = {}; + patch[name] = method; + _.mixin(patch, { chain: chain }); + } else { + _[name] = method; + } } + return _; + } + return mixOrPatchIn; +} - _bare() { +module.exports = getMixOrPatchIn; - const obj = this.clone(); - obj._reset(); - const terms = obj._definition.terms; - for (const name in terms) { - const term = terms[name]; - obj.$_terms[name] = term.init; - } +/***/ }), - return obj.$_mutateRebuild(); - } +/***/ 86564: +/***/ ((module) => { - _default(flag, value, options = {}) { +"use strict"; - Common.assertOptions(options, 'literal'); - Assert(value !== undefined, 'Missing', flag, 'value'); - Assert(typeof value === 'function' || !options.literal, 'Only function value supports literal option'); +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} - if (typeof value === 'function' && - options.literal) { +module.exports = isObject; - value = { - [Common.symbols.literal]: true, - literal: value - }; - } - const obj = this.$_setFlag(flag, value); - return obj; - } +/***/ }), - _generate(value, state, prefs) { +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { - if (!this.$_terms.whens) { - return { schema: this }; - } +"use strict"; - // Collect matching whens - const whens = []; - const ids = []; - for (let i = 0; i < this.$_terms.whens.length; ++i) { - const when = this.$_terms.whens[i]; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (when.concat) { - whens.push(when.concat); - ids.push(`${i}.concat`); - continue; - } +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - const input = when.ref ? when.ref.resolve(value, state, prefs) : value; - const tests = when.is ? [when] : when.switch; - const before = ids.length; + /* istanbul ignore next */ - for (let j = 0; j < tests.length; ++j) { - const { is, then, otherwise } = tests[j]; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } - const baseId = `${i}${when.switch ? '.' + j : ''}`; - if (is.$_match(input, state.nest(is, `${baseId}.is`), prefs)) { - if (then) { - const localState = state.localize([...state.path, `${baseId}.then`], state.ancestors, state.schemas); - const { schema: generated, id } = then._generate(value, localState, prefs); - whens.push(generated); - ids.push(`${baseId}.then${id ? `(${id})` : ''}`); - break; - } - } - else if (otherwise) { - const localState = state.localize([...state.path, `${baseId}.otherwise`], state.ancestors, state.schemas); - const { schema: generated, id } = otherwise._generate(value, localState, prefs); - whens.push(generated); - ids.push(`${baseId}.otherwise${id ? `(${id})` : ''}`); - break; - } - } + this.name = 'Deprecation'; + } - if (when.break && - ids.length > before) { // Something matched +} - break; - } - } +exports.Deprecation = Deprecation; - // Check cache - const id = ids.join(', '); - state.mainstay.tracer.debug(state, 'rule', 'when', id); +/***/ }), - if (!id) { - return { schema: this }; - } +/***/ 11848: +/***/ ((module) => { - if (!state.mainstay.tracer.active && - this.$_temp.whens[id]) { +"use strict"; - return { schema: this.$_temp.whens[id], id }; - } - // Generate dynamic schema +var has = Object.prototype.hasOwnProperty + , prefix = '~'; - let obj = this; // eslint-disable-line consistent-this - if (this._definition.generate) { - obj = this._definition.generate(this, value, state, prefs); - } +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} - // Apply whens +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); - for (const when of whens) { - obj = obj.concat(when); - } + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} - // Tracing +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} - if (this.$_root._tracer) { - this.$_root._tracer._combine(obj, [this, ...whens]); - } +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } - // Cache result + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; - this.$_temp.whens[id] = obj; - return { schema: obj, id }; - } + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; - _inner(type, values, options = {}) { + return emitter; +} - Assert(!this._inRuleset(), `Cannot set ${type} inside a ruleset`); +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} - const obj = this.clone(); - if (!obj.$_terms[type] || - options.override) { +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} - obj.$_terms[type] = []; - } +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; - if (options.single) { - obj.$_terms[type].push(values); - } - else { - obj.$_terms[type].push(...values); - } + if (this._eventsCount === 0) return names; - obj.$_temp.ruleset = false; - return obj; - } + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } - _inRuleset() { + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } - return this.$_temp.ruleset !== null && this.$_temp.ruleset !== false; - } + return names; +}; - _ruleRemove(name, options = {}) { +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; - if (!this._singleRules.has(name)) { - return this; - } + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; - const obj = options.clone !== false ? this.clone() : this; + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } - obj._singleRules.delete(name); + return ee; +}; - const filtered = []; - for (let i = 0; i < obj._rules.length; ++i) { - const test = obj._rules[i]; - if (test.name === name && - !test.keep) { +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; - if (obj._inRuleset() && - i < obj.$_temp.ruleset) { + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; - --obj.$_temp.ruleset; - } +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; - continue; - } + if (!this._events[evt]) return false; - filtered.push(test); - } + var listeners = this._events[evt] + , len = arguments.length + , args + , i; - obj._rules = filtered; - return obj; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } - _values(values, key) { + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } - Common.verifyFlat(values, key.slice(1, -1)); + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; - const obj = this.clone(); + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - const override = values[0] === Common.symbols.override; - if (override) { - values = values.slice(1); - } + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } - if (!obj[key] && - values.length) { + listeners[i].fn.apply(listeners[i].context, args); + } + } + } - obj[key] = new Values(); - } - else if (override) { - obj[key] = values.length ? new Values() : null; - obj.$_mutateRebuild(); - } + return true; +}; - if (!obj[key]) { - return obj; - } +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; - if (override) { - obj[key].override(); - } +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; - for (const value of values) { - Assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); - Assert(value !== Common.symbols.override, 'Override must be the first value'); +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; - const other = key === '_invalids' ? '_valids' : '_invalids'; - if (obj[other]) { - obj[other].remove(value); - if (!obj[other].length) { - Assert(key === '_valids' || !obj._flags.only, 'Setting invalid value', value, 'leaves schema rejecting all values due to previous valid rule'); - obj[other] = null; - } - } + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } - obj[key].add(value, obj._refs); - } + var listeners = this._events[evt]; - return obj; + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } } -}; + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } -internals.Base.prototype[Common.symbols.any] = { - version: Common.version, - compile: Compile.compile, - root: '$_root' + return this; }; +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; -internals.Base.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects (must be on prototype) + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + return this; +}; -// Aliases +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; -internals.Base.prototype.deny = internals.Base.prototype.invalid; -internals.Base.prototype.disallow = internals.Base.prototype.invalid; -internals.Base.prototype.equal = internals.Base.prototype.valid; -internals.Base.prototype.exist = internals.Base.prototype.required; -internals.Base.prototype.not = internals.Base.prototype.invalid; -internals.Base.prototype.options = internals.Base.prototype.prefs; -internals.Base.prototype.preferences = internals.Base.prototype.prefs; +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; -module.exports = new internals.Base(); +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; +} /***/ }), -/***/ 63355: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); +Object.defineProperty(exports, "__esModule", ({ value: true })); -const Common = __nccwpck_require__(72448); +/*! + * 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]'; +} -const internals = { - max: 1000, - supported: new Set(['undefined', 'boolean', 'number', 'string']) -}; +function isPlainObject(o) { + var ctor,prot; + if (isObject(o) === false) return false; -exports.provider = { + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; - provision(options) { + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; - return new internals.Cache(options); - } -}; + // 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; + + +/***/ }), + +/***/ 46014: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Clone = __nccwpck_require__(85578); +const Common = __nccwpck_require__(72448); -// Least Recently Used (LRU) Cache -internals.Cache = class { +const internals = { + annotations: Symbol('annotations') +}; - constructor(options = {}) { - Common.assertOptions(options, ['max']); - Assert(options.max === undefined || options.max && options.max > 0 && isFinite(options.max), 'Invalid max cache size'); +exports.error = function (stripColorCodes) { - this._max = options.max || internals.max; + if (!this._original || + typeof this._original !== 'object') { - this._map = new Map(); // Map of nodes by key - this._list = new internals.List(); // List of nodes (most recently used in head) + return this.details[0].message; } - get length() { + const redFgEscape = stripColorCodes ? '' : '\u001b[31m'; + const redBgEscape = stripColorCodes ? '' : '\u001b[41m'; + const endColor = stripColorCodes ? '' : '\u001b[0m'; - return this._map.size; - } + const obj = Clone(this._original); - set(key, value) { + for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first + const pos = i + 1; + const error = this.details[i]; + const path = error.path; + let node = obj; + for (let j = 0; ; ++j) { + const seg = path[j]; - if (key !== null && - !internals.supported.has(typeof key)) { + if (Common.isSchema(node)) { + node = node.clone(); // joi schemas are not cloned by hoek, we have to take this extra step + } - return; - } + if (j + 1 < path.length && + typeof node[seg] !== 'string') { - let node = this._map.get(key); - if (node) { - node.value = value; - this._list.first(node); - return; - } + node = node[seg]; + } + else { + const refAnnotations = node[internals.annotations] || { errors: {}, missing: {} }; + node[internals.annotations] = refAnnotations; - node = this._list.unshift({ key, value }); - this._map.set(key, node); - this._compact(); - } + const cacheKey = seg || error.context.key; - get(key) { + if (node[seg] !== undefined) { + refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || []; + refAnnotations.errors[cacheKey].push(pos); + } + else { + refAnnotations.missing[cacheKey] = pos; + } - const node = this._map.get(key); - if (node) { - this._list.first(node); - return Clone(node.value); + break; + } } } - _compact() { + const replacers = { + key: /_\$key\$_([, \d]+)_\$end\$_"/g, + missing: /"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g, + arrayIndex: /\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g, + specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g + }; - if (this._map.size > this._max) { - const node = this._list.pop(); - this._map.delete(node.key); - } + let message = internals.safeStringify(obj, 2) + .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`) + .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`) + .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`) + .replace(replacers.specials, ($0, $1) => $1); + + message = `${message}\n${redFgEscape}`; + + for (let i = 0; i < this.details.length; ++i) { + const pos = i + 1; + message = `${message}\n[${pos}] ${this.details[i].message}`; } + + message = message + endColor; + + return message; }; -internals.List = class { +// Inspired by json-stringify-safe - constructor() { +internals.safeStringify = function (obj, spaces) { - this.tail = null; - this.head = null; - } + return JSON.stringify(obj, internals.serializer(), spaces); +}; - unshift(node) { - node.next = null; - node.prev = this.head; +internals.serializer = function () { - if (this.head) { - this.head.next = node; - } + const keys = []; + const stack = []; - this.head = node; + const cycleReplacer = (key, value) => { - if (!this.tail) { - this.tail = node; + if (stack[0] === value) { + return '[Circular ~]'; } - return node; - } + return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; + }; - first(node) { + return function (key, value) { - if (node === this.head) { - return; - } + if (stack.length > 0) { + const thisPos = stack.indexOf(this); + if (~thisPos) { + stack.length = thisPos + 1; + keys.length = thisPos + 1; + keys[thisPos] = key; + } + else { + stack.push(this); + keys.push(key); + } - this._remove(node); - this.unshift(node); - } + if (~stack.indexOf(value)) { + value = cycleReplacer.call(this, key, value); + } + } + else { + stack.push(value); + } - pop() { + if (value) { + const annotations = value[internals.annotations]; + if (annotations) { + if (Array.isArray(value)) { + const annotated = []; - return this._remove(this.tail); - } + for (let i = 0; i < value.length; ++i) { + if (annotations.errors[i]) { + annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`); + } - _remove(node) { + annotated.push(value[i]); + } - const { next, prev } = node; + value = annotated; + } + else { + for (const errorKey in annotations.errors) { + value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey]; + value[errorKey] = undefined; + } - next.prev = prev; + for (const missingKey in annotations.missing) { + value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__'; + } + } - if (prev) { - prev.next = next; + return value; + } } - if (node === this.tail) { - this.tail = next; - } + if (value === Infinity || + value === -Infinity || + Number.isNaN(value) || + typeof value === 'function' || + typeof value === 'symbol') { - node.prev = null; - node.next = null; + return '[' + value.toString() + ']'; + } - return node; - } + return value; + }; }; /***/ }), -/***/ 72448: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 95184: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Assert = __nccwpck_require__(32718); -const AssertError = __nccwpck_require__(35563); - -const Pkg = __nccwpck_require__(77045); - -let Messages; -let Schemas; - +const Clone = __nccwpck_require__(85578); +const DeepEqual = __nccwpck_require__(55801); +const Merge = __nccwpck_require__(60445); -const internals = { - isoDate: /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/ -}; +const Cache = __nccwpck_require__(63355); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Extend = __nccwpck_require__(86680); +const Manifest = __nccwpck_require__(87997); +const Messages = __nccwpck_require__(86103); +const Modify = __nccwpck_require__(81290); +const Ref = __nccwpck_require__(73838); +const Trace = __nccwpck_require__(43171); +const Validator = __nccwpck_require__(91804); +const Values = __nccwpck_require__(71944); -exports.version = Pkg.version; +const internals = {}; -exports.defaults = { - abortEarly: true, - allowUnknown: false, - artifacts: false, - cache: true, - context: null, - convert: true, - dateFormat: 'iso', - errors: { - escapeHtml: false, - label: 'path', - language: null, - render: true, - stack: false, - wrap: { - label: '"', - array: '[]' - } - }, - externals: true, - messages: {}, - nonEnumerables: false, - noDefaults: false, - presence: 'optional', - skipFunctions: false, - stripUnknown: false, - warnings: false -}; +internals.Base = class { + constructor(type) { -exports.symbols = { - any: Symbol.for('@hapi/joi/schema'), // Used to internally identify any-based types (shared with other joi versions) - arraySingle: Symbol('arraySingle'), - deepDefault: Symbol('deepDefault'), - errors: Symbol('errors'), - literal: Symbol('literal'), - override: Symbol('override'), - parent: Symbol('parent'), - prefs: Symbol('prefs'), - ref: Symbol('ref'), - template: Symbol('template'), - values: Symbol('values') -}; + // Naming: public, _private, $_extension, $_mutate{action} + this.type = type; -exports.assertOptions = function (options, keys, name = 'Options') { + this.$_root = null; + this._definition = {}; + this._reset(); + } - Assert(options && typeof options === 'object' && !Array.isArray(options), 'Options must be of type object'); - const unknownKeys = Object.keys(options).filter((k) => !keys.includes(k)); - Assert(unknownKeys.length === 0, `${name} contain unknown keys: ${unknownKeys}`); -}; + _reset() { + this._ids = new Modify.Ids(); + this._preferences = null; + this._refs = new Ref.Manager(); + this._cache = null; -exports.checkPreferences = function (prefs) { + this._valids = null; + this._invalids = null; - Schemas = Schemas || __nccwpck_require__(85614); + this._flags = {}; + this._rules = []; + this._singleRules = new Map(); // The rule options passed for non-multi rules - const result = Schemas.preferences.validate(prefs); + this.$_terms = {}; // Hash of arrays of immutable objects (extended by other types) - if (result.error) { - throw new AssertError([result.error.details[0].message]); + this.$_temp = { // Runtime state (not cloned) + ruleset: null, // null: use last, false: error, number: start position + whens: {} // Runtime cache of generated whens + }; } -}; + // Manifest -exports.compare = function (a, b, operator) { + describe() { - switch (operator) { - case '=': return a === b; - case '>': return a > b; - case '<': return a < b; - case '>=': return a >= b; - case '<=': return a <= b; + Assert(typeof Manifest.describe === 'function', 'Manifest functionality disabled'); + return Manifest.describe(this); } -}; - - -exports["default"] = function (value, defaultValue) { - return value === undefined ? defaultValue : value; -}; + // Rules + allow(...values) { -exports.isIsoDate = function (date) { + Common.verifyFlat(values, 'allow'); + return this._values(values, '_valids'); + } - return internals.isoDate.test(date); -}; + alter(targets) { + Assert(targets && typeof targets === 'object' && !Array.isArray(targets), 'Invalid targets argument'); + Assert(!this._inRuleset(), 'Cannot set alterations inside a ruleset'); -exports.isNumber = function (value) { + const obj = this.clone(); + obj.$_terms.alterations = obj.$_terms.alterations || []; + for (const target in targets) { + const adjuster = targets[target]; + Assert(typeof adjuster === 'function', 'Alteration adjuster for', target, 'must be a function'); + obj.$_terms.alterations.push({ target, adjuster }); + } - return typeof value === 'number' && !isNaN(value); -}; + obj.$_temp.ruleset = false; + return obj; + } + artifact(id) { -exports.isResolvable = function (obj) { + Assert(id !== undefined, 'Artifact cannot be undefined'); + Assert(!this._cache, 'Cannot set an artifact with a rule cache'); - if (!obj) { - return false; + return this.$_setFlag('artifact', id); } - return obj[exports.symbols.ref] || obj[exports.symbols.template]; -}; - + cast(to) { -exports.isSchema = function (schema, options = {}) { + Assert(to === false || typeof to === 'string', 'Invalid to value'); + Assert(to === false || this._definition.cast[to], 'Type', this.type, 'does not support casting to', to); - const any = schema && schema[exports.symbols.any]; - if (!any) { - return false; + return this.$_setFlag('cast', to === false ? undefined : to); } - Assert(options.legacy || any.version === exports.version, 'Cannot mix different versions of joi schemas'); - return true; -}; - + default(value, options) { -exports.isValues = function (obj) { + return this._default('default', value, options); + } - return obj[exports.symbols.values]; -}; + description(desc) { + Assert(desc && typeof desc === 'string', 'Description must be a non-empty string'); -exports.limit = function (value) { + return this.$_setFlag('description', desc); + } - return Number.isSafeInteger(value) && value >= 0; -}; + empty(schema) { + const obj = this.clone(); -exports.preferences = function (target, source) { + if (schema !== undefined) { + schema = obj.$_compile(schema, { override: false }); + } - Messages = Messages || __nccwpck_require__(86103); + return obj.$_setFlag('empty', schema, { clone: false }); + } - target = target || {}; - source = source || {}; + error(err) { - const merged = Object.assign({}, target, source); - if (source.errors && - target.errors) { + Assert(err, 'Missing error'); + Assert(err instanceof Error || typeof err === 'function', 'Must provide a valid Error object or a function'); - merged.errors = Object.assign({}, target.errors, source.errors); - merged.errors.wrap = Object.assign({}, target.errors.wrap, source.errors.wrap); + return this.$_setFlag('error', err); } - if (source.messages) { - merged.messages = Messages.compile(source.messages, target.messages); - } + example(example, options = {}) { - delete merged[exports.symbols.prefs]; - return merged; -}; + Assert(example !== undefined, 'Missing example'); + Common.assertOptions(options, ['override']); + return this._inner('examples', example, { single: true, override: options.override }); + } -exports.tryWithPath = function (fn, key, options = {}) { + external(method, description) { - try { - return fn(); - } - catch (err) { - if (err.path !== undefined) { - err.path = key + '.' + err.path; - } - else { - err.path = key; + if (typeof method === 'object') { + Assert(!description, 'Cannot combine options with description'); + description = method.description; + method = method.method; } - if (options.append) { - err.message = `${err.message} (${err.path})`; - } + Assert(typeof method === 'function', 'Method must be a function'); + Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); - throw err; + return this._inner('externals', { method, description }, { single: true }); } -}; - -exports.validateArg = function (value, label, { assert, message }) { - - if (exports.isSchema(assert)) { - const result = assert.validate(value); - if (!result.error) { - return; - } + failover(value, options) { - return result.error.message; - } - else if (!assert(value)) { - return label ? `${label} ${message}` : message; + return this._default('failover', value, options); } -}; + forbidden() { -exports.verifyFlat = function (args, method) { - - for (const arg of args) { - Assert(!Array.isArray(arg), 'Method no longer accepts array arguments:', method); + return this.presence('forbidden'); } -}; - -/***/ }), + id(id) { -/***/ 3038: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!id) { + return this.$_setFlag('id', undefined); + } -"use strict"; + Assert(typeof id === 'string', 'id must be a non-empty string'); + Assert(/^[^\.]+$/.test(id), 'id cannot contain period character'); + return this.$_setFlag('id', id); + } -const Assert = __nccwpck_require__(32718); + invalid(...values) { -const Common = __nccwpck_require__(72448); -const Ref = __nccwpck_require__(73838); + return this._values(values, '_invalids'); + } + label(name) { -const internals = {}; + Assert(name && typeof name === 'string', 'Label name must be a non-empty string'); + return this.$_setFlag('label', name); + } -exports.schema = function (Joi, config, options = {}) { + meta(meta) { - Common.assertOptions(options, ['appendPath', 'override']); + Assert(meta !== undefined, 'Meta cannot be undefined'); - try { - return internals.schema(Joi, config, options); + return this._inner('metas', meta, { single: true }); } - catch (err) { - if (options.appendPath && - err.path !== undefined) { - err.message = `${err.message} (${err.path})`; + note(...notes) { + + Assert(notes.length, 'Missing notes'); + for (const note of notes) { + Assert(note && typeof note === 'string', 'Notes must be non-empty strings'); } - throw err; + return this._inner('notes', notes); } -}; + only(mode = true) { -internals.schema = function (Joi, config, options) { - - Assert(config !== undefined, 'Invalid undefined schema'); - - if (Array.isArray(config)) { - Assert(config.length, 'Invalid empty array schema'); + Assert(typeof mode === 'boolean', 'Invalid mode:', mode); - if (config.length === 1) { - config = config[0]; - } + return this.$_setFlag('only', mode); } - const valid = (base, ...values) => { + optional() { - if (options.override !== false) { - return base.valid(Joi.override, ...values); - } + return this.presence('optional'); + } - return base.valid(...values); - }; + prefs(prefs) { - if (internals.simple(config)) { - return valid(Joi, config); - } + Assert(prefs, 'Missing preferences'); + Assert(prefs.context === undefined, 'Cannot override context'); + Assert(prefs.externals === undefined, 'Cannot override externals'); + Assert(prefs.warnings === undefined, 'Cannot override warnings'); + Assert(prefs.debug === undefined, 'Cannot override debug'); - if (typeof config === 'function') { - return Joi.custom(config); + Common.checkPreferences(prefs); + + const obj = this.clone(); + obj._preferences = Common.preferences(obj._preferences, prefs); + return obj; } - Assert(typeof config === 'object', 'Invalid schema content:', typeof config); + presence(mode) { - if (Common.isResolvable(config)) { - return valid(Joi, config); - } + Assert(['optional', 'required', 'forbidden'].includes(mode), 'Unknown presence mode', mode); - if (Common.isSchema(config)) { - return config; + return this.$_setFlag('presence', mode); } - if (Array.isArray(config)) { - for (const item of config) { - if (!internals.simple(item)) { - return Joi.alternatives().try(...config); - } - } + raw(enabled = true) { - return valid(Joi, ...config); + return this.$_setFlag('result', enabled ? 'raw' : undefined); } - if (config instanceof RegExp) { - return Joi.string().regex(config); - } + result(mode) { - if (config instanceof Date) { - return valid(Joi.date(), config); + Assert(['raw', 'strip'].includes(mode), 'Unknown result mode', mode); + + return this.$_setFlag('result', mode); } - Assert(Object.getPrototypeOf(config) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); + required() { - return Joi.object().keys(config); -}; + return this.presence('required'); + } + strict(enabled) { -exports.ref = function (id, options) { + const obj = this.clone(); - return Ref.isRef(id) ? id : Ref.create(id, options); -}; + const convert = enabled === undefined ? false : !enabled; + obj._preferences = Common.preferences(obj._preferences, { convert }); + return obj; + } + strip(enabled = true) { -exports.compile = function (root, schema, options = {}) { + return this.$_setFlag('result', enabled ? 'strip' : undefined); + } - Common.assertOptions(options, ['legacy']); + tag(...tags) { - // Compiled by any supported version + Assert(tags.length, 'Missing tags'); + for (const tag of tags) { + Assert(tag && typeof tag === 'string', 'Tags must be non-empty strings'); + } - const any = schema && schema[Common.symbols.any]; - if (any) { - Assert(options.legacy || any.version === Common.version, 'Cannot mix different versions of joi schemas:', any.version, Common.version); - return schema; + return this._inner('tags', tags); } - // Uncompiled root + unit(name) { - if (typeof schema !== 'object' || - !options.legacy) { + Assert(name && typeof name === 'string', 'Unit name must be a non-empty string'); - return exports.schema(root, schema, { appendPath: true }); // Will error if schema contains other versions + return this.$_setFlag('unit', name); } - // Scan schema for compiled parts + valid(...values) { - const compiler = internals.walk(schema); - if (!compiler) { - return exports.schema(root, schema, { appendPath: true }); + Common.verifyFlat(values, 'valid'); + + const obj = this.allow(...values); + obj.$_setFlag('only', !!obj._valids, { clone: false }); + return obj; } - return compiler.compile(compiler.root, schema); -}; + when(condition, options) { + const obj = this.clone(); -internals.walk = function (schema) { + if (!obj.$_terms.whens) { + obj.$_terms.whens = []; + } - if (typeof schema !== 'object') { - return null; - } + const when = Compile.when(obj, condition, options); + if (!['any', 'link'].includes(obj.type)) { + const conditions = when.is ? [when] : when.switch; + for (const item of conditions) { + Assert(!item.then || item.then.type === 'any' || item.then.type === obj.type, 'Cannot combine', obj.type, 'with', item.then && item.then.type); + Assert(!item.otherwise || item.otherwise.type === 'any' || item.otherwise.type === obj.type, 'Cannot combine', obj.type, 'with', item.otherwise && item.otherwise.type); - if (Array.isArray(schema)) { - for (const item of schema) { - const compiler = internals.walk(item); - if (compiler) { - return compiler; } } - return null; + obj.$_terms.whens.push(when); + return obj.$_mutateRebuild(); } - const any = schema[Common.symbols.any]; - if (any) { - return { root: schema[any.root], compile: any.compile }; - } + // Helpers - Assert(Object.getPrototypeOf(schema) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); + cache(cache) { - for (const key in schema) { - const compiler = internals.walk(schema[key]); - if (compiler) { - return compiler; - } + Assert(!this._inRuleset(), 'Cannot set caching inside a ruleset'); + Assert(!this._cache, 'Cannot override schema cache'); + Assert(this._flags.artifact === undefined, 'Cannot cache a rule with an artifact'); + + const obj = this.clone(); + obj._cache = cache || Cache.provider.provision(); + obj.$_temp.ruleset = false; + return obj; } - return null; -}; + clone() { + const obj = Object.create(Object.getPrototypeOf(this)); + return this._assign(obj); + } -internals.simple = function (value) { + concat(source) { - return value === null || ['boolean', 'string', 'number'].includes(typeof value); -}; + Assert(Common.isSchema(source), 'Invalid schema object'); + Assert(this.type === 'any' || source.type === 'any' || source.type === this.type, 'Cannot merge type', this.type, 'with another type:', source.type); + Assert(!this._inRuleset(), 'Cannot concatenate onto a schema with open ruleset'); + Assert(!source._inRuleset(), 'Cannot concatenate a schema with open ruleset'); + let obj = this.clone(); -exports.when = function (schema, condition, options) { + if (this.type === 'any' && + source.type !== 'any') { - if (options === undefined) { - Assert(condition && typeof condition === 'object', 'Missing options'); + // Change obj to match source type - options = condition; - condition = Ref.create('.'); - } + const tmpObj = source.clone(); + for (const key of Object.keys(obj)) { + if (key !== 'type') { + tmpObj[key] = obj[key]; + } + } - if (Array.isArray(options)) { - options = { switch: options }; - } + obj = tmpObj; + } - Common.assertOptions(options, ['is', 'not', 'then', 'otherwise', 'switch', 'break']); + obj._ids.concat(source._ids); + obj._refs.register(source, Ref.toSibling); - // Schema condition + obj._preferences = obj._preferences ? Common.preferences(obj._preferences, source._preferences) : source._preferences; + obj._valids = Values.merge(obj._valids, source._valids, source._invalids); + obj._invalids = Values.merge(obj._invalids, source._invalids, source._valids); - if (Common.isSchema(condition)) { - Assert(options.is === undefined, '"is" can not be used with a schema condition'); - Assert(options.not === undefined, '"not" can not be used with a schema condition'); - Assert(options.switch === undefined, '"switch" can not be used with a schema condition'); + // Remove unique rules present in source - return internals.condition(schema, { is: condition, then: options.then, otherwise: options.otherwise, break: options.break }); - } + for (const name of source._singleRules.keys()) { + if (obj._singleRules.has(name)) { + obj._rules = obj._rules.filter((target) => target.keep || target.name !== name); + obj._singleRules.delete(name); + } + } - // Single condition + // Rules - Assert(Ref.isRef(condition) || typeof condition === 'string', 'Invalid condition:', condition); - Assert(options.not === undefined || options.is === undefined, 'Cannot combine "is" with "not"'); + for (const test of source._rules) { + if (!source._definition.rules[test.method].multi) { + obj._singleRules.set(test.name, test); + } - if (options.switch === undefined) { - let rule = options; - if (options.not !== undefined) { - rule = { is: options.not, then: options.otherwise, otherwise: options.then, break: options.break }; + obj._rules.push(test); } - let is = rule.is !== undefined ? schema.$_compile(rule.is) : schema.$_root.invalid(null, false, 0, '').required(); - Assert(rule.then !== undefined || rule.otherwise !== undefined, 'options must have at least one of "then", "otherwise", or "switch"'); - Assert(rule.break === undefined || rule.then === undefined || rule.otherwise === undefined, 'Cannot specify then, otherwise, and break all together'); + // Flags - if (options.is !== undefined && - !Ref.isRef(options.is) && - !Common.isSchema(options.is)) { + if (obj._flags.empty && + source._flags.empty) { - is = is.required(); // Only apply required if this wasn't already a schema or a ref + obj._flags.empty = obj._flags.empty.concat(source._flags.empty); + const flags = Object.assign({}, source._flags); + delete flags.empty; + Merge(obj._flags, flags); + } + else if (source._flags.empty) { + obj._flags.empty = source._flags.empty; + const flags = Object.assign({}, source._flags); + delete flags.empty; + Merge(obj._flags, flags); + } + else { + Merge(obj._flags, source._flags); } - return internals.condition(schema, { ref: exports.ref(condition), is, then: rule.then, otherwise: rule.otherwise, break: rule.break }); - } + // Terms - // Switch statement + for (const key in source.$_terms) { + const terms = source.$_terms[key]; + if (!terms) { + if (!obj.$_terms[key]) { + obj.$_terms[key] = terms; + } - Assert(Array.isArray(options.switch), '"switch" must be an array'); - Assert(options.is === undefined, 'Cannot combine "switch" with "is"'); - Assert(options.not === undefined, 'Cannot combine "switch" with "not"'); - Assert(options.then === undefined, 'Cannot combine "switch" with "then"'); + continue; + } - const rule = { - ref: exports.ref(condition), - switch: [], - break: options.break - }; + if (!obj.$_terms[key]) { + obj.$_terms[key] = terms.slice(); + continue; + } - for (let i = 0; i < options.switch.length; ++i) { - const test = options.switch[i]; - const last = i === options.switch.length - 1; + obj.$_terms[key] = obj.$_terms[key].concat(terms); + } - Common.assertOptions(test, last ? ['is', 'then', 'otherwise'] : ['is', 'then']); + // Tracing - Assert(test.is !== undefined, 'Switch statement missing "is"'); - Assert(test.then !== undefined, 'Switch statement missing "then"'); + if (this.$_root._tracer) { + this.$_root._tracer._combine(obj, [this, source]); + } - const item = { - is: schema.$_compile(test.is), - then: schema.$_compile(test.then) - }; + // Rebuild - if (!Ref.isRef(test.is) && - !Common.isSchema(test.is)) { + return obj.$_mutateRebuild(); + } - item.is = item.is.required(); // Only apply required if this wasn't already a schema or a ref - } + extend(options) { - if (last) { - Assert(options.otherwise === undefined || test.otherwise === undefined, 'Cannot specify "otherwise" inside and outside a "switch"'); - const otherwise = options.otherwise !== undefined ? options.otherwise : test.otherwise; - if (otherwise !== undefined) { - Assert(rule.break === undefined, 'Cannot specify both otherwise and break'); - item.otherwise = schema.$_compile(otherwise); - } - } + Assert(!options.base, 'Cannot extend type with another base'); - rule.switch.push(item); + return Extend.type(this, options); } - return rule; -}; + extract(path) { + path = Array.isArray(path) ? path : path.split('.'); + return this._ids.reach(path); + } -internals.condition = function (schema, condition) { + fork(paths, adjuster) { - for (const key of ['then', 'otherwise']) { - if (condition[key] === undefined) { - delete condition[key]; - } - else { - condition[key] = schema.$_compile(condition[key]); + Assert(!this._inRuleset(), 'Cannot fork inside a ruleset'); + + let obj = this; // eslint-disable-line consistent-this + for (let path of [].concat(paths)) { + path = Array.isArray(path) ? path : path.split('.'); + obj = obj._ids.fork(path, adjuster, obj); } + + obj.$_temp.ruleset = false; + return obj; } - return condition; -}; + rule(options) { + const def = this._definition; + Common.assertOptions(options, Object.keys(def.modifiers)); -/***/ }), + Assert(this.$_temp.ruleset !== false, 'Cannot apply rules to empty ruleset or the last rule added does not support rule properties'); + const start = this.$_temp.ruleset === null ? this._rules.length - 1 : this.$_temp.ruleset; + Assert(start >= 0 && start < this._rules.length, 'Cannot apply rules to empty ruleset'); -/***/ 69490: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const obj = this.clone(); -"use strict"; + for (let i = start; i < obj._rules.length; ++i) { + const original = obj._rules[i]; + const rule = Clone(original); + for (const name in options) { + def.modifiers[name](rule, options[name]); + Assert(rule.name === original.name, 'Cannot change rule name'); + } -const Annotate = __nccwpck_require__(46014); -const Common = __nccwpck_require__(72448); -const Template = __nccwpck_require__(51396); + obj._rules[i] = rule; + if (obj._singleRules.get(rule.name) === original) { + obj._singleRules.set(rule.name, rule); + } + } -const internals = {}; + obj.$_temp.ruleset = false; + return obj.$_mutateRebuild(); + } + get ruleset() { -exports.Report = class { + Assert(!this._inRuleset(), 'Cannot start a new ruleset without closing the previous one'); - constructor(code, value, local, flags, messages, state, prefs) { + const obj = this.clone(); + obj.$_temp.ruleset = obj._rules.length; + return obj; + } - this.code = code; - this.flags = flags; - this.messages = messages; - this.path = state.path; - this.prefs = prefs; - this.state = state; - this.value = value; + get $() { - this.message = null; - this.template = null; + return this.ruleset; + } - this.local = local || {}; - this.local.label = exports.label(this.flags, this.state, this.prefs, this.messages); + tailor(targets) { - if (this.value !== undefined && - !this.local.hasOwnProperty('value')) { + targets = [].concat(targets); - this.local.value = this.value; - } + Assert(!this._inRuleset(), 'Cannot tailor inside a ruleset'); - if (this.path.length) { - const key = this.path[this.path.length - 1]; - if (typeof key !== 'object') { - this.local.key = key; + let obj = this; // eslint-disable-line consistent-this + + if (this.$_terms.alterations) { + for (const { target, adjuster } of this.$_terms.alterations) { + if (targets.includes(target)) { + obj = adjuster(obj); + Assert(Common.isSchema(obj), 'Alteration adjuster for', target, 'failed to return a schema object'); + } } } + + obj = obj.$_modify({ each: (item) => item.tailor(targets), ref: false }); + obj.$_temp.ruleset = false; + return obj.$_mutateRebuild(); } - _setTemplate(template) { + tracer() { - this.template = template; + return Trace.location ? Trace.location(this) : this; // $lab:coverage:ignore$ + } - if (!this.flags.label && - this.path.length === 0) { + validate(value, options) { - const localized = this._template(this.template, 'root'); - if (localized) { - this.local.label = localized; - } - } + return Validator.entry(value, this, options); } - toString() { + validateAsync(value, options) { - if (this.message) { - return this.message; - } + return Validator.entryAsync(value, this, options); + } - const code = this.code; + // Extensions - if (!this.prefs.errors.render) { - return this.code; - } + $_addRule(options) { - const template = this._template(this.template) || - this._template(this.prefs.messages) || - this._template(this.messages); + // Normalize rule - if (template === undefined) { - return `Error code "${code}" is not defined, your custom type is missing the correct messages definition`; + if (typeof options === 'string') { + options = { name: options }; } - // Render and cache result + Assert(options && typeof options === 'object', 'Invalid options'); + Assert(options.name && typeof options.name === 'string', 'Invalid rule name'); - this.message = template.render(this.value, this.state, this.prefs, this.local, { errors: this.prefs.errors, messages: [this.prefs.messages, this.messages] }); - if (!this.prefs.errors.label) { - this.message = this.message.replace(/^"" /, '').trim(); + for (const key in options) { + Assert(key[0] !== '_', 'Cannot set private rule properties'); } - return this.message; - } - - _template(messages, code) { + const rule = Object.assign({}, options); // Shallow cloned + rule._resolve = []; + rule.method = rule.method || rule.name; - return exports.template(this.value, messages, code || this.code, this.state, this.prefs); - } -}; + const definition = this._definition.rules[rule.method]; + const args = rule.args; + Assert(definition, 'Unknown rule', rule.method); -exports.path = function (path) { + // Args - let label = ''; - for (const segment of path) { - if (typeof segment === 'object') { // Exclude array single path segment - continue; - } + const obj = this.clone(); - if (typeof segment === 'string') { - if (label) { - label += '.'; - } + if (args) { + Assert(Object.keys(args).length === 1 || Object.keys(args).length === this._definition.rules[rule.name].args.length, 'Invalid rule definition for', this.type, rule.name); - label += segment; - } - else { - label += `[${segment}]`; - } - } + for (const key in args) { + let arg = args[key]; - return label; -}; + if (definition.argsByName) { + const resolver = definition.argsByName.get(key); + if (resolver.ref && + Common.isResolvable(arg)) { -exports.template = function (value, messages, code, state, prefs) { + rule._resolve.push(key); + obj.$_mutateRegister(arg); + } + else { + if (resolver.normalize) { + arg = resolver.normalize(arg); + args[key] = arg; + } - if (!messages) { - return; - } + if (resolver.assert) { + const error = Common.validateArg(arg, key, resolver); + Assert(!error, error, 'or reference'); + } + } + } - if (Template.isTemplate(messages)) { - return code !== 'root' ? messages : null; - } + if (arg === undefined) { + delete args[key]; + continue; + } - let lang = prefs.errors.language; - if (Common.isResolvable(lang)) { - lang = lang.resolve(value, state, prefs); - } + args[key] = arg; + } + } - if (lang && - messages[lang]) { + // Unique rules - if (messages[lang][code] !== undefined) { - return messages[lang][code]; + if (!definition.multi) { + obj._ruleRemove(rule.name, { clone: false }); + obj._singleRules.set(rule.name, rule); } - if (messages[lang]['*'] !== undefined) { - return messages[lang]['*']; + if (obj.$_temp.ruleset === false) { + obj.$_temp.ruleset = null; } - } - if (!messages[code]) { - return messages['*']; + if (definition.priority) { + obj._rules.unshift(rule); + } + else { + obj._rules.push(rule); + } + + return obj; } - return messages[code]; -}; + $_compile(schema, options) { + return Compile.schema(this.$_root, schema, options); + } -exports.label = function (flags, state, prefs, messages) { + $_createError(code, value, local, state, prefs, options = {}) { - if (flags.label) { - return flags.label; + const flags = options.flags !== false ? this._flags : {}; + const messages = options.messages ? Messages.merge(this._definition.messages, options.messages) : this._definition.messages; + return new Errors.Report(code, value, local, flags, messages, state, prefs); } - if (!prefs.errors.label) { - return ''; + $_getFlag(name) { + + return this._flags[name]; } - let path = state.path; - if (prefs.errors.label === 'key' && - state.path.length > 1) { + $_getRule(name) { - path = state.path.slice(-1); + return this._singleRules.get(name); } - const normalized = exports.path(path); - if (normalized) { - return normalized; + $_mapLabels(path) { + + path = Array.isArray(path) ? path : path.split('.'); + return this._ids.labels(path); } - return exports.template(null, prefs.messages, 'root', state, prefs) || - messages && exports.template(null, messages, 'root', state, prefs) || - 'value'; -}; + $_match(value, state, prefs, overrides) { + prefs = Object.assign({}, prefs); // Shallow cloned + prefs.abortEarly = true; + prefs._externals = false; -exports.process = function (errors, original, prefs) { + state.snapshot(); + const result = !Validator.validate(value, this, state, prefs, overrides).errors; + state.restore(); - if (!errors) { - return null; + return result; } - const { override, message, details } = exports.details(errors); - if (override) { - return override; - } + $_modify(options) { - if (prefs.errors.stack) { - return new exports.ValidationError(message, details, original); + Common.assertOptions(options, ['each', 'once', 'ref', 'schema']); + return Modify.schema(this, options) || this; } - const limit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - const validationError = new exports.ValidationError(message, details, original); - Error.stackTraceLimit = limit; - return validationError; -}; - - -exports.details = function (errors, options = {}) { + $_mutateRebuild() { - let messages = []; - const details = []; + Assert(!this._inRuleset(), 'Cannot add this rule inside a ruleset'); - for (const item of errors) { + this._refs.reset(); + this._ids.reset(); - // Override + const each = (item, { source, name, path, key }) => { - if (item instanceof Error) { - if (options.override !== false) { - return { override: item }; + const family = this._definition[source][name] && this._definition[source][name].register; + if (family !== false) { + this.$_mutateRegister(item, { family, key }); } + }; - const message = item.toString(); - messages.push(message); - - details.push({ - message, - type: 'override', - context: { error: item } - }); + this.$_modify({ each }); - continue; + if (this._definition.rebuild) { + this._definition.rebuild(this); } - // Report - - const message = item.toString(); - messages.push(message); - - details.push({ - message, - path: item.path.filter((v) => typeof v !== 'object'), - type: item.code, - context: item.local - }); - } - - if (messages.length > 1) { - messages = [...new Set(messages)]; + this.$_temp.ruleset = false; + return this; } - return { message: messages.join('. '), details }; -}; - + $_mutateRegister(schema, { family, key } = {}) { -exports.ValidationError = class extends Error { + this._refs.register(schema, family); + this._ids.register(schema, { key }); + } - constructor(message, details, original) { + $_property(name) { - super(message); - this._original = original; - this.details = details; + return this._definition.properties[name]; } - static isError(err) { + $_reach(path) { - return err instanceof exports.ValidationError; + return this._ids.reach(path); } -}; + $_rootReferences() { -exports.ValidationError.prototype.isJoi = true; - -exports.ValidationError.prototype.name = 'ValidationError'; + return this._refs.roots(); + } -exports.ValidationError.prototype.annotate = Annotate.error; + $_setFlag(name, value, options = {}) { + Assert(name[0] === '_' || !this._inRuleset(), 'Cannot set flag inside a ruleset'); -/***/ }), + const flag = this._definition.flags[name] || {}; + if (DeepEqual(value, flag.default)) { + value = undefined; + } -/***/ 86680: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (DeepEqual(value, this._flags[name])) { + return this; + } -"use strict"; + const obj = options.clone !== false ? this.clone() : this; + if (value !== undefined) { + obj._flags[name] = value; + obj.$_mutateRegister(value); + } + else { + delete obj._flags[name]; + } -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); + if (name[0] !== '_') { + obj.$_temp.ruleset = false; + } -const Common = __nccwpck_require__(72448); -const Messages = __nccwpck_require__(86103); + return obj; + } + $_parent(method, ...args) { -const internals = {}; + return this[method][Common.symbols.parent].call(this, ...args); + } + $_validate(value, state, prefs) { -exports.type = function (from, options) { + return Validator.validate(value, this, state, prefs); + } - const base = Object.getPrototypeOf(from); - const prototype = Clone(base); - const schema = from._assign(Object.create(prototype)); - const def = Object.assign({}, options); // Shallow cloned - delete def.base; + // Internals - prototype._definition = def; + _assign(target) { - const parent = base._definition || {}; - def.messages = Messages.merge(parent.messages, def.messages); - def.properties = Object.assign({}, parent.properties, def.properties); + target.type = this.type; - // Type + target.$_root = this.$_root; - schema.type = def.type; + target.$_temp = Object.assign({}, this.$_temp); + target.$_temp.whens = {}; - // Flags + target._ids = this._ids.clone(); + target._preferences = this._preferences; + target._valids = this._valids && this._valids.clone(); + target._invalids = this._invalids && this._invalids.clone(); + target._rules = this._rules.slice(); + target._singleRules = Clone(this._singleRules, { shallow: true }); + target._refs = this._refs.clone(); + target._flags = Object.assign({}, this._flags); + target._cache = null; - def.flags = Object.assign({}, parent.flags, def.flags); + target.$_terms = {}; + for (const key in this.$_terms) { + target.$_terms[key] = this.$_terms[key] ? this.$_terms[key].slice() : null; + } - // Terms + // Backwards compatibility - const terms = Object.assign({}, parent.terms); - if (def.terms) { - for (const name in def.terms) { // Only apply own terms - const term = def.terms[name]; - Assert(schema.$_terms[name] === undefined, 'Invalid term override for', def.type, name); - schema.$_terms[name] = term.init; - terms[name] = term; + target.$_super = {}; + for (const override in this.$_super) { + target.$_super[override] = this._super[override].bind(target); } + + return target; } - def.terms = terms; + _bare() { - // Constructor arguments + const obj = this.clone(); + obj._reset(); - if (!def.args) { - def.args = parent.args; - } + const terms = obj._definition.terms; + for (const name in terms) { + const term = terms[name]; + obj.$_terms[name] = term.init; + } - // Prepare + return obj.$_mutateRebuild(); + } - def.prepare = internals.prepare(def.prepare, parent.prepare); + _default(flag, value, options = {}) { - // Coerce + Common.assertOptions(options, 'literal'); - if (def.coerce) { - if (typeof def.coerce === 'function') { - def.coerce = { method: def.coerce }; - } + Assert(value !== undefined, 'Missing', flag, 'value'); + Assert(typeof value === 'function' || !options.literal, 'Only function value supports literal option'); - if (def.coerce.from && - !Array.isArray(def.coerce.from)) { + if (typeof value === 'function' && + options.literal) { - def.coerce = { method: def.coerce.method, from: [].concat(def.coerce.from) }; + value = { + [Common.symbols.literal]: true, + literal: value + }; } - } - - def.coerce = internals.coerce(def.coerce, parent.coerce); - // Validate + const obj = this.$_setFlag(flag, value); + return obj; + } - def.validate = internals.validate(def.validate, parent.validate); + _generate(value, state, prefs) { - // Rules + if (!this.$_terms.whens) { + return { schema: this }; + } - const rules = Object.assign({}, parent.rules); - if (def.rules) { - for (const name in def.rules) { - const rule = def.rules[name]; - Assert(typeof rule === 'object', 'Invalid rule definition for', def.type, name); + // Collect matching whens - let method = rule.method; - if (method === undefined) { - method = function () { + const whens = []; + const ids = []; + for (let i = 0; i < this.$_terms.whens.length; ++i) { + const when = this.$_terms.whens[i]; - return this.$_addRule(name); - }; + if (when.concat) { + whens.push(when.concat); + ids.push(`${i}.concat`); + continue; } - if (method) { - Assert(!prototype[name], 'Rule conflict in', def.type, name); - prototype[name] = method; - } + const input = when.ref ? when.ref.resolve(value, state, prefs) : value; + const tests = when.is ? [when] : when.switch; + const before = ids.length; - Assert(!rules[name], 'Rule conflict in', def.type, name); - rules[name] = rule; + for (let j = 0; j < tests.length; ++j) { + const { is, then, otherwise } = tests[j]; - if (rule.alias) { - const aliases = [].concat(rule.alias); - for (const alias of aliases) { - prototype[alias] = rule.method; + const baseId = `${i}${when.switch ? '.' + j : ''}`; + if (is.$_match(input, state.nest(is, `${baseId}.is`), prefs)) { + if (then) { + const localState = state.localize([...state.path, `${baseId}.then`], state.ancestors, state.schemas); + const { schema: generated, id } = then._generate(value, localState, prefs); + whens.push(generated); + ids.push(`${baseId}.then${id ? `(${id})` : ''}`); + break; + } + } + else if (otherwise) { + const localState = state.localize([...state.path, `${baseId}.otherwise`], state.ancestors, state.schemas); + const { schema: generated, id } = otherwise._generate(value, localState, prefs); + whens.push(generated); + ids.push(`${baseId}.otherwise${id ? `(${id})` : ''}`); + break; } } - if (rule.args) { - rule.argsByName = new Map(); - rule.args = rule.args.map((arg) => { - - if (typeof arg === 'string') { - arg = { name: arg }; - } - - Assert(!rule.argsByName.has(arg.name), 'Duplicated argument name', arg.name); - - if (Common.isSchema(arg.assert)) { - arg.assert = arg.assert.strict().label(arg.name); - } + if (when.break && + ids.length > before) { // Something matched - rule.argsByName.set(arg.name, arg); - return arg; - }); + break; } } - } - - def.rules = rules; - - // Modifiers - const modifiers = Object.assign({}, parent.modifiers); - if (def.modifiers) { - for (const name in def.modifiers) { - Assert(!prototype[name], 'Rule conflict in', def.type, name); + // Check cache - const modifier = def.modifiers[name]; - Assert(typeof modifier === 'function', 'Invalid modifier definition for', def.type, name); + const id = ids.join(', '); + state.mainstay.tracer.debug(state, 'rule', 'when', id); - const method = function (arg) { + if (!id) { + return { schema: this }; + } - return this.rule({ [name]: arg }); - }; + if (!state.mainstay.tracer.active && + this.$_temp.whens[id]) { - prototype[name] = method; - modifiers[name] = modifier; + return { schema: this.$_temp.whens[id], id }; } - } - def.modifiers = modifiers; - - // Overrides + // Generate dynamic schema - if (def.overrides) { - prototype._super = base; - schema.$_super = {}; // Backwards compatibility - for (const override in def.overrides) { - Assert(base[override], 'Cannot override missing', override); - def.overrides[override][Common.symbols.parent] = base[override]; - schema.$_super[override] = base[override].bind(schema); // Backwards compatibility + let obj = this; // eslint-disable-line consistent-this + if (this._definition.generate) { + obj = this._definition.generate(this, value, state, prefs); } - Object.assign(prototype, def.overrides); - } - - // Casts + // Apply whens - def.cast = Object.assign({}, parent.cast, def.cast); + for (const when of whens) { + obj = obj.concat(when); + } - // Manifest + // Tracing - const manifest = Object.assign({}, parent.manifest, def.manifest); - manifest.build = internals.build(def.manifest && def.manifest.build, parent.manifest && parent.manifest.build); - def.manifest = manifest; + if (this.$_root._tracer) { + this.$_root._tracer._combine(obj, [this, ...whens]); + } - // Rebuild + // Cache result - def.rebuild = internals.rebuild(def.rebuild, parent.rebuild); + this.$_temp.whens[id] = obj; + return { schema: obj, id }; + } - return schema; -}; + _inner(type, values, options = {}) { + Assert(!this._inRuleset(), `Cannot set ${type} inside a ruleset`); -// Helpers + const obj = this.clone(); + if (!obj.$_terms[type] || + options.override) { -internals.build = function (child, parent) { + obj.$_terms[type] = []; + } - if (!child || - !parent) { + if (options.single) { + obj.$_terms[type].push(values); + } + else { + obj.$_terms[type].push(...values); + } - return child || parent; + obj.$_temp.ruleset = false; + return obj; } - return function (obj, desc) { - - return parent(child(obj, desc), desc); - }; -}; - - -internals.coerce = function (child, parent) { - - if (!child || - !parent) { + _inRuleset() { - return child || parent; + return this.$_temp.ruleset !== null && this.$_temp.ruleset !== false; } - return { - from: child.from && parent.from ? [...new Set([...child.from, ...parent.from])] : null, - method(value, helpers) { + _ruleRemove(name, options = {}) { - let coerced; - if (!parent.from || - parent.from.includes(typeof value)) { + if (!this._singleRules.has(name)) { + return this; + } - coerced = parent.method(value, helpers); - if (coerced) { - if (coerced.errors || - coerced.value === undefined) { + const obj = options.clone !== false ? this.clone() : this; - return coerced; - } + obj._singleRules.delete(name); - value = coerced.value; - } - } + const filtered = []; + for (let i = 0; i < obj._rules.length; ++i) { + const test = obj._rules[i]; + if (test.name === name && + !test.keep) { - if (!child.from || - child.from.includes(typeof value)) { + if (obj._inRuleset() && + i < obj.$_temp.ruleset) { - const own = child.method(value, helpers); - if (own) { - return own; + --obj.$_temp.ruleset; } + + continue; } - return coerced; + filtered.push(test); } - }; -}; - - -internals.prepare = function (child, parent) { - if (!child || - !parent) { - - return child || parent; + obj._rules = filtered; + return obj; } - return function (value, helpers) { + _values(values, key) { - const prepared = child(value, helpers); - if (prepared) { - if (prepared.errors || - prepared.value === undefined) { + Common.verifyFlat(values, key.slice(1, -1)); - return prepared; - } + const obj = this.clone(); - value = prepared.value; + const override = values[0] === Common.symbols.override; + if (override) { + values = values.slice(1); } - return parent(value, helpers) || prepared; - }; -}; + if (!obj[key] && + values.length) { + obj[key] = new Values(); + } + else if (override) { + obj[key] = values.length ? new Values() : null; + obj.$_mutateRebuild(); + } -internals.rebuild = function (child, parent) { + if (!obj[key]) { + return obj; + } - if (!child || - !parent) { + if (override) { + obj[key].override(); + } - return child || parent; - } + for (const value of values) { + Assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); + Assert(value !== Common.symbols.override, 'Override must be the first value'); - return function (schema) { + const other = key === '_invalids' ? '_valids' : '_invalids'; + if (obj[other]) { + obj[other].remove(value); + if (!obj[other].length) { + Assert(key === '_valids' || !obj._flags.only, 'Setting invalid value', value, 'leaves schema rejecting all values due to previous valid rule'); + obj[other] = null; + } + } - parent(schema); - child(schema); - }; + obj[key].add(value, obj._refs); + } + + return obj; + } }; -internals.validate = function (child, parent) { +internals.Base.prototype[Common.symbols.any] = { + version: Common.version, + compile: Compile.compile, + root: '$_root' +}; - if (!child || - !parent) { - return child || parent; - } +internals.Base.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects (must be on prototype) - return function (value, helpers) { - const result = parent(value, helpers); - if (result) { - if (result.errors && - (!Array.isArray(result.errors) || result.errors.length)) { +// Aliases - return result; - } +internals.Base.prototype.deny = internals.Base.prototype.invalid; +internals.Base.prototype.disallow = internals.Base.prototype.invalid; +internals.Base.prototype.equal = internals.Base.prototype.valid; +internals.Base.prototype.exist = internals.Base.prototype.required; +internals.Base.prototype.not = internals.Base.prototype.invalid; +internals.Base.prototype.options = internals.Base.prototype.prefs; +internals.Base.prototype.preferences = internals.Base.prototype.prefs; - value = result.value; - } - return child(value, helpers) || result; - }; -}; +module.exports = new internals.Base(); /***/ }), -/***/ 20918: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 63355: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -22702,4813 +23198,4602 @@ internals.validate = function (child, parent) { const Assert = __nccwpck_require__(32718); const Clone = __nccwpck_require__(85578); -const Cache = __nccwpck_require__(63355); const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Extend = __nccwpck_require__(86680); -const Manifest = __nccwpck_require__(87997); -const Ref = __nccwpck_require__(73838); -const Template = __nccwpck_require__(51396); -const Trace = __nccwpck_require__(43171); - -let Schemas; const internals = { - types: { - alternatives: __nccwpck_require__(26867), - any: __nccwpck_require__(9512), - array: __nccwpck_require__(20270), - boolean: __nccwpck_require__(47489), - date: __nccwpck_require__(6624), - function: __nccwpck_require__(62269), - link: __nccwpck_require__(69869), - number: __nccwpck_require__(15855), - object: __nccwpck_require__(46878), - string: __nccwpck_require__(72260), - symbol: __nccwpck_require__(40971) - }, - aliases: { - alt: 'alternatives', - bool: 'boolean', - func: 'function' - } + max: 1000, + supported: new Set(['undefined', 'boolean', 'number', 'string']) }; -if (Buffer) { // $lab:coverage:ignore$ - internals.types.binary = __nccwpck_require__(34288); -} +exports.provider = { + provision(options) { -internals.root = function () { + return new internals.Cache(options); + } +}; - const root = { - _types: new Set(Object.keys(internals.types)) - }; - // Types +// Least Recently Used (LRU) Cache - for (const type of root._types) { - root[type] = function (...args) { +internals.Cache = class { - Assert(!args.length || ['alternatives', 'link', 'object'].includes(type), 'The', type, 'type does not allow arguments'); - return internals.generate(this, internals.types[type], args); - }; - } + constructor(options = {}) { - // Shortcuts + Common.assertOptions(options, ['max']); + Assert(options.max === undefined || options.max && options.max > 0 && isFinite(options.max), 'Invalid max cache size'); - for (const method of ['allow', 'custom', 'disallow', 'equal', 'exist', 'forbidden', 'invalid', 'not', 'only', 'optional', 'options', 'prefs', 'preferences', 'required', 'strip', 'valid', 'when']) { - root[method] = function (...args) { + this._max = options.max || internals.max; - return this.any()[method](...args); - }; + this._map = new Map(); // Map of nodes by key + this._list = new internals.List(); // List of nodes (most recently used in head) } - // Methods + get length() { - Object.assign(root, internals.methods); + return this._map.size; + } - // Aliases + set(key, value) { - for (const alias in internals.aliases) { - const target = internals.aliases[alias]; - root[alias] = root[target]; - } + if (key !== null && + !internals.supported.has(typeof key)) { - root.x = root.expression; + return; + } - // Trace + let node = this._map.get(key); + if (node) { + node.value = value; + this._list.first(node); + return; + } - if (Trace.setup) { // $lab:coverage:ignore$ - Trace.setup(root); + node = this._list.unshift({ key, value }); + this._map.set(key, node); + this._compact(); } - return root; -}; + get(key) { + const node = this._map.get(key); + if (node) { + this._list.first(node); + return Clone(node.value); + } + } -internals.methods = { + _compact() { - ValidationError: Errors.ValidationError, - version: Common.version, - cache: Cache.provider, + if (this._map.size > this._max) { + const node = this._list.pop(); + this._map.delete(node.key); + } + } +}; - assert(value, schema, ...args /* [message], [options] */) { - internals.assert(value, schema, true, args); - }, +internals.List = class { - attempt(value, schema, ...args /* [message], [options] */) { + constructor() { - return internals.assert(value, schema, false, args); - }, + this.tail = null; + this.head = null; + } - build(desc) { + unshift(node) { - Assert(typeof Manifest.build === 'function', 'Manifest functionality disabled'); - return Manifest.build(this, desc); - }, + node.next = null; + node.prev = this.head; - checkPreferences(prefs) { + if (this.head) { + this.head.next = node; + } - Common.checkPreferences(prefs); - }, + this.head = node; - compile(schema, options) { + if (!this.tail) { + this.tail = node; + } - return Compile.compile(this, schema, options); - }, + return node; + } - defaults(modifier) { + first(node) { - Assert(typeof modifier === 'function', 'modifier must be a function'); + if (node === this.head) { + return; + } - const joi = Object.assign({}, this); - for (const type of joi._types) { - const schema = modifier(joi[type]()); - Assert(Common.isSchema(schema), 'modifier must return a valid schema object'); + this._remove(node); + this.unshift(node); + } - joi[type] = function (...args) { + pop() { - return internals.generate(this, schema, args); - }; - } + return this._remove(this.tail); + } - return joi; - }, + _remove(node) { - expression(...args) { + const { next, prev } = node; - return new Template(...args); - }, + next.prev = prev; - extend(...extensions) { + if (prev) { + prev.next = next; + } - Common.verifyFlat(extensions, 'extend'); + if (node === this.tail) { + this.tail = next; + } - Schemas = Schemas || __nccwpck_require__(85614); + node.prev = null; + node.next = null; - Assert(extensions.length, 'You need to provide at least one extension'); - this.assert(extensions, Schemas.extensions); + return node; + } +}; - const joi = Object.assign({}, this); - joi._types = new Set(joi._types); - for (let extension of extensions) { - if (typeof extension === 'function') { - extension = extension(joi); - } +/***/ }), - this.assert(extension, Schemas.extension); +/***/ 72448: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const expanded = internals.expandExtension(extension, joi); - for (const item of expanded) { - Assert(joi[item.type] === undefined || joi._types.has(item.type), 'Cannot override name', item.type); +"use strict"; - const base = item.base || this.any(); - const schema = Extend.type(base, item); - joi._types.add(item.type); - joi[item.type] = function (...args) { +const Assert = __nccwpck_require__(32718); +const AssertError = __nccwpck_require__(35563); - return internals.generate(this, schema, args); - }; - } - } +const Pkg = __nccwpck_require__(77045); - return joi; - }, +let Messages; +let Schemas; - isError: Errors.ValidationError.isError, - isExpression: Template.isTemplate, - isRef: Ref.isRef, - isSchema: Common.isSchema, - in(...args) { +const internals = { + isoDate: /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/ +}; - return Ref.in(...args); - }, - override: Common.symbols.override, +exports.version = Pkg.version; - ref(...args) { - return Ref.create(...args); +exports.defaults = { + abortEarly: true, + allowUnknown: false, + artifacts: false, + cache: true, + context: null, + convert: true, + dateFormat: 'iso', + errors: { + escapeHtml: false, + label: 'path', + language: null, + render: true, + stack: false, + wrap: { + label: '"', + array: '[]' + } }, + externals: true, + messages: {}, + nonEnumerables: false, + noDefaults: false, + presence: 'optional', + skipFunctions: false, + stripUnknown: false, + warnings: false +}; - types() { - const types = {}; - for (const type of this._types) { - types[type] = this[type](); - } +exports.symbols = { + any: Symbol.for('@hapi/joi/schema'), // Used to internally identify any-based types (shared with other joi versions) + arraySingle: Symbol('arraySingle'), + deepDefault: Symbol('deepDefault'), + errors: Symbol('errors'), + literal: Symbol('literal'), + override: Symbol('override'), + parent: Symbol('parent'), + prefs: Symbol('prefs'), + ref: Symbol('ref'), + template: Symbol('template'), + values: Symbol('values') +}; - for (const target in internals.aliases) { - types[target] = this[target](); - } - return types; - } +exports.assertOptions = function (options, keys, name = 'Options') { + + Assert(options && typeof options === 'object' && !Array.isArray(options), 'Options must be of type object'); + const unknownKeys = Object.keys(options).filter((k) => !keys.includes(k)); + Assert(unknownKeys.length === 0, `${name} contain unknown keys: ${unknownKeys}`); }; -// Helpers +exports.checkPreferences = function (prefs) { -internals.assert = function (value, schema, annotate, args /* [message], [options] */) { + Schemas = Schemas || __nccwpck_require__(85614); - const message = args[0] instanceof Error || typeof args[0] === 'string' ? args[0] : null; - const options = message !== null ? args[1] : args[0]; - const result = schema.validate(value, Common.preferences({ errors: { stack: true } }, options || {})); + const result = Schemas.preferences.validate(prefs); - let error = result.error; - if (!error) { - return result.value; + if (result.error) { + throw new AssertError([result.error.details[0].message]); } +}; - if (message instanceof Error) { - throw message; - } - const display = annotate && typeof error.annotate === 'function' ? error.annotate() : error.message; +exports.compare = function (a, b, operator) { - if (error instanceof Errors.ValidationError === false) { - error = Clone(error); + switch (operator) { + case '=': return a === b; + case '>': return a > b; + case '<': return a < b; + case '>=': return a >= b; + case '<=': return a <= b; } - - error.message = message ? `${message} ${display}` : display; - throw error; }; -internals.generate = function (root, schema, args) { - - Assert(root, 'Must be invoked on a Joi instance.'); +exports["default"] = function (value, defaultValue) { - schema.$_root = root; + return value === undefined ? defaultValue : value; +}; - if (!schema._definition.args || - !args.length) { - return schema; - } +exports.isIsoDate = function (date) { - return schema._definition.args(schema, ...args); + return internals.isoDate.test(date); }; -internals.expandExtension = function (extension, joi) { - - if (typeof extension.type === 'string') { - return [extension]; - } - - const extended = []; - for (const type of joi._types) { - if (extension.type.test(type)) { - const item = Object.assign({}, extension); - item.type = type; - item.base = joi[type](); - extended.push(item); - } - } +exports.isNumber = function (value) { - return extended; + return typeof value === 'number' && !isNaN(value); }; -module.exports = internals.root(); +exports.isResolvable = function (obj) { + if (!obj) { + return false; + } -/***/ }), + return obj[exports.symbols.ref] || obj[exports.symbols.template]; +}; -/***/ 87997: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +exports.isSchema = function (schema, options = {}) { + const any = schema && schema[exports.symbols.any]; + if (!any) { + return false; + } -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); + Assert(options.legacy || any.version === exports.version, 'Cannot mix different versions of joi schemas'); + return true; +}; -const Common = __nccwpck_require__(72448); -const Messages = __nccwpck_require__(86103); -const Ref = __nccwpck_require__(73838); -const Template = __nccwpck_require__(51396); -let Schemas; +exports.isValues = function (obj) { + return obj[exports.symbols.values]; +}; -const internals = {}; +exports.limit = function (value) { -exports.describe = function (schema) { + return Number.isSafeInteger(value) && value >= 0; +}; - const def = schema._definition; - // Type +exports.preferences = function (target, source) { - const desc = { - type: schema.type, - flags: {}, - rules: [] - }; + Messages = Messages || __nccwpck_require__(86103); - // Flags + target = target || {}; + source = source || {}; - for (const flag in schema._flags) { - if (flag[0] !== '_') { - desc.flags[flag] = internals.describe(schema._flags[flag]); - } - } + const merged = Object.assign({}, target, source); + if (source.errors && + target.errors) { - if (!Object.keys(desc.flags).length) { - delete desc.flags; + merged.errors = Object.assign({}, target.errors, source.errors); + merged.errors.wrap = Object.assign({}, target.errors.wrap, source.errors.wrap); } - // Preferences - - if (schema._preferences) { - desc.preferences = Clone(schema._preferences, { shallow: ['messages'] }); - delete desc.preferences[Common.symbols.prefs]; - if (desc.preferences.messages) { - desc.preferences.messages = Messages.decompile(desc.preferences.messages); - } + if (source.messages) { + merged.messages = Messages.compile(source.messages, target.messages); } - // Allow / Invalid - - if (schema._valids) { - desc.allow = schema._valids.describe(); - } + delete merged[exports.symbols.prefs]; + return merged; +}; - if (schema._invalids) { - desc.invalid = schema._invalids.describe(); - } - // Rules +exports.tryWithPath = function (fn, key, options = {}) { - for (const rule of schema._rules) { - const ruleDef = def.rules[rule.name]; - if (ruleDef.manifest === false) { // Defaults to true - continue; + try { + return fn(); + } + catch (err) { + if (err.path !== undefined) { + err.path = key + '.' + err.path; + } + else { + err.path = key; } - const item = { name: rule.name }; - - for (const custom in def.modifiers) { - if (rule[custom] !== undefined) { - item[custom] = internals.describe(rule[custom]); - } + if (options.append) { + err.message = `${err.message} (${err.path})`; } - if (rule.args) { - item.args = {}; - for (const key in rule.args) { - const arg = rule.args[key]; - if (key === 'options' && - !Object.keys(arg).length) { + throw err; + } +}; - continue; - } - item.args[key] = internals.describe(arg, { assign: key }); - } +exports.validateArg = function (value, label, { assert, message }) { - if (!Object.keys(item.args).length) { - delete item.args; - } + if (exports.isSchema(assert)) { + const result = assert.validate(value); + if (!result.error) { + return; } - desc.rules.push(item); + return result.error.message; } - - if (!desc.rules.length) { - delete desc.rules; + else if (!assert(value)) { + return label ? `${label} ${message}` : message; } +}; - // Terms (must be last to verify no name conflicts) - - for (const term in schema.$_terms) { - if (term[0] === '_') { - continue; - } - Assert(!desc[term], 'Cannot describe schema due to internal name conflict with', term); +exports.verifyFlat = function (args, method) { - const items = schema.$_terms[term]; - if (!items) { - continue; - } + for (const arg of args) { + Assert(!Array.isArray(arg), 'Method no longer accepts array arguments:', method); + } +}; - if (items instanceof Map) { - if (items.size) { - desc[term] = [...items.entries()]; - } - continue; - } +/***/ }), - if (Common.isValues(items)) { - desc[term] = items.describe(); - continue; - } +/***/ 3038: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Assert(def.terms[term], 'Term', term, 'missing configuration'); - const manifest = def.terms[term].manifest; - const mapped = typeof manifest === 'object'; - if (!items.length && - !mapped) { +"use strict"; - continue; - } - const normalized = []; - for (const item of items) { - normalized.push(internals.describe(item)); - } +const Assert = __nccwpck_require__(32718); - // Mapped +const Common = __nccwpck_require__(72448); +const Ref = __nccwpck_require__(73838); - if (mapped) { - const { from, to } = manifest.mapped; - desc[term] = {}; - for (const item of normalized) { - desc[term][item[to]] = item[from]; - } - continue; - } +const internals = {}; - // Single - if (manifest === 'single') { - Assert(normalized.length === 1, 'Term', term, 'contains more than one item'); - desc[term] = normalized[0]; - continue; - } +exports.schema = function (Joi, config, options = {}) { - // Array + Common.assertOptions(options, ['appendPath', 'override']); - desc[term] = normalized; + try { + return internals.schema(Joi, config, options); } + catch (err) { + if (options.appendPath && + err.path !== undefined) { - internals.validate(schema.$_root, desc); - return desc; -}; + err.message = `${err.message} (${err.path})`; + } + throw err; + } +}; -internals.describe = function (item, options = {}) { - if (Array.isArray(item)) { - return item.map(internals.describe); - } +internals.schema = function (Joi, config, options) { - if (item === Common.symbols.deepDefault) { - return { special: 'deep' }; - } + Assert(config !== undefined, 'Invalid undefined schema'); - if (typeof item !== 'object' || - item === null) { + if (Array.isArray(config)) { + Assert(config.length, 'Invalid empty array schema'); - return item; + if (config.length === 1) { + config = config[0]; + } } - if (options.assign === 'options') { - return Clone(item); - } + const valid = (base, ...values) => { - if (Buffer && Buffer.isBuffer(item)) { // $lab:coverage:ignore$ - return { buffer: item.toString('binary') }; - } + if (options.override !== false) { + return base.valid(Joi.override, ...values); + } - if (item instanceof Date) { - return item.toISOString(); + return base.valid(...values); + }; + + if (internals.simple(config)) { + return valid(Joi, config); } - if (item instanceof Error) { - return item; + if (typeof config === 'function') { + return Joi.custom(config); } - if (item instanceof RegExp) { - if (options.assign === 'regex') { - return item.toString(); - } + Assert(typeof config === 'object', 'Invalid schema content:', typeof config); - return { regex: item.toString() }; + if (Common.isResolvable(config)) { + return valid(Joi, config); } - if (item[Common.symbols.literal]) { - return { function: item.literal }; + if (Common.isSchema(config)) { + return config; } - if (typeof item.describe === 'function') { - if (options.assign === 'ref') { - return item.describe().ref; + if (Array.isArray(config)) { + for (const item of config) { + if (!internals.simple(item)) { + return Joi.alternatives().try(...config); + } } - return item.describe(); + return valid(Joi, ...config); } - const normalized = {}; - for (const key in item) { - const value = item[key]; - if (value === undefined) { - continue; - } + if (config instanceof RegExp) { + return Joi.string().regex(config); + } - normalized[key] = internals.describe(value, { assign: key }); + if (config instanceof Date) { + return valid(Joi.date(), config); } - return normalized; + Assert(Object.getPrototypeOf(config) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); + + return Joi.object().keys(config); }; -exports.build = function (joi, desc) { +exports.ref = function (id, options) { - const builder = new internals.Builder(joi); - return builder.parse(desc); + return Ref.isRef(id) ? id : Ref.create(id, options); }; -internals.Builder = class { +exports.compile = function (root, schema, options = {}) { - constructor(joi) { + Common.assertOptions(options, ['legacy']); - this.joi = joi; - } + // Compiled by any supported version - parse(desc) { + const any = schema && schema[Common.symbols.any]; + if (any) { + Assert(options.legacy || any.version === Common.version, 'Cannot mix different versions of joi schemas:', any.version, Common.version); + return schema; + } - internals.validate(this.joi, desc); + // Uncompiled root - // Type + if (typeof schema !== 'object' || + !options.legacy) { - let schema = this.joi[desc.type]()._bare(); - const def = schema._definition; + return exports.schema(root, schema, { appendPath: true }); // Will error if schema contains other versions + } - // Flags + // Scan schema for compiled parts - if (desc.flags) { - for (const flag in desc.flags) { - const setter = def.flags[flag] && def.flags[flag].setter || flag; - Assert(typeof schema[setter] === 'function', 'Invalid flag', flag, 'for type', desc.type); - schema = schema[setter](this.build(desc.flags[flag])); - } - } + const compiler = internals.walk(schema); + if (!compiler) { + return exports.schema(root, schema, { appendPath: true }); + } - // Preferences + return compiler.compile(compiler.root, schema); +}; - if (desc.preferences) { - schema = schema.preferences(this.build(desc.preferences)); - } - // Allow / Invalid +internals.walk = function (schema) { - if (desc.allow) { - schema = schema.allow(...this.build(desc.allow)); - } + if (typeof schema !== 'object') { + return null; + } - if (desc.invalid) { - schema = schema.invalid(...this.build(desc.invalid)); + if (Array.isArray(schema)) { + for (const item of schema) { + const compiler = internals.walk(item); + if (compiler) { + return compiler; + } } - // Rules - - if (desc.rules) { - for (const rule of desc.rules) { - Assert(typeof schema[rule.name] === 'function', 'Invalid rule', rule.name, 'for type', desc.type); - - const args = []; - if (rule.args) { - const built = {}; - for (const key in rule.args) { - built[key] = this.build(rule.args[key], { assign: key }); - } - - const keys = Object.keys(built); - const definition = def.rules[rule.name].args; - if (definition) { - Assert(keys.length <= definition.length, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to', definition.length, ', found', keys.length, ')'); - for (const { name } of definition) { - args.push(built[name]); - } - } - else { - Assert(keys.length === 1, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to 1, found', keys.length, ')'); - args.push(built[keys[0]]); - } - } + return null; + } - // Apply + const any = schema[Common.symbols.any]; + if (any) { + return { root: schema[any.root], compile: any.compile }; + } - schema = schema[rule.name](...args); + Assert(Object.getPrototypeOf(schema) === Object.getPrototypeOf({}), 'Schema can only contain plain objects'); - // Ruleset + for (const key in schema) { + const compiler = internals.walk(schema[key]); + if (compiler) { + return compiler; + } + } - const options = {}; - for (const custom in def.modifiers) { - if (rule[custom] !== undefined) { - options[custom] = this.build(rule[custom]); - } - } + return null; +}; - if (Object.keys(options).length) { - schema = schema.rule(options); - } - } - } - // Terms +internals.simple = function (value) { - const terms = {}; - for (const key in desc) { - if (['allow', 'flags', 'invalid', 'whens', 'preferences', 'rules', 'type'].includes(key)) { - continue; - } + return value === null || ['boolean', 'string', 'number'].includes(typeof value); +}; - Assert(def.terms[key], 'Term', key, 'missing configuration'); - const manifest = def.terms[key].manifest; - if (manifest === 'schema') { - terms[key] = desc[key].map((item) => this.parse(item)); - continue; - } +exports.when = function (schema, condition, options) { - if (manifest === 'values') { - terms[key] = desc[key].map((item) => this.build(item)); - continue; - } + if (options === undefined) { + Assert(condition && typeof condition === 'object', 'Missing options'); - if (manifest === 'single') { - terms[key] = this.build(desc[key]); - continue; - } + options = condition; + condition = Ref.create('.'); + } - if (typeof manifest === 'object') { - terms[key] = {}; - for (const name in desc[key]) { - const value = desc[key][name]; - terms[key][name] = this.parse(value); - } + if (Array.isArray(options)) { + options = { switch: options }; + } - continue; - } + Common.assertOptions(options, ['is', 'not', 'then', 'otherwise', 'switch', 'break']); - terms[key] = this.build(desc[key]); - } + // Schema condition - if (desc.whens) { - terms.whens = desc.whens.map((when) => this.build(when)); - } + if (Common.isSchema(condition)) { + Assert(options.is === undefined, '"is" can not be used with a schema condition'); + Assert(options.not === undefined, '"not" can not be used with a schema condition'); + Assert(options.switch === undefined, '"switch" can not be used with a schema condition'); - schema = def.manifest.build(schema, terms); - schema.$_temp.ruleset = false; - return schema; + return internals.condition(schema, { is: condition, then: options.then, otherwise: options.otherwise, break: options.break }); } - build(desc, options = {}) { - - if (desc === null) { - return null; - } + // Single condition - if (Array.isArray(desc)) { - return desc.map((item) => this.build(item)); - } + Assert(Ref.isRef(condition) || typeof condition === 'string', 'Invalid condition:', condition); + Assert(options.not === undefined || options.is === undefined, 'Cannot combine "is" with "not"'); - if (desc instanceof Error) { - return desc; + if (options.switch === undefined) { + let rule = options; + if (options.not !== undefined) { + rule = { is: options.not, then: options.otherwise, otherwise: options.then, break: options.break }; } - if (options.assign === 'options') { - return Clone(desc); - } + let is = rule.is !== undefined ? schema.$_compile(rule.is) : schema.$_root.invalid(null, false, 0, '').required(); + Assert(rule.then !== undefined || rule.otherwise !== undefined, 'options must have at least one of "then", "otherwise", or "switch"'); + Assert(rule.break === undefined || rule.then === undefined || rule.otherwise === undefined, 'Cannot specify then, otherwise, and break all together'); - if (options.assign === 'regex') { - return internals.regex(desc); - } + if (options.is !== undefined && + !Ref.isRef(options.is) && + !Common.isSchema(options.is)) { - if (options.assign === 'ref') { - return Ref.build(desc); + is = is.required(); // Only apply required if this wasn't already a schema or a ref } - if (typeof desc !== 'object') { - return desc; - } + return internals.condition(schema, { ref: exports.ref(condition), is, then: rule.then, otherwise: rule.otherwise, break: rule.break }); + } - if (Object.keys(desc).length === 1) { - if (desc.buffer) { - Assert(Buffer, 'Buffers are not supported'); - return Buffer && Buffer.from(desc.buffer, 'binary'); // $lab:coverage:ignore$ - } + // Switch statement - if (desc.function) { - return { [Common.symbols.literal]: true, literal: desc.function }; - } + Assert(Array.isArray(options.switch), '"switch" must be an array'); + Assert(options.is === undefined, 'Cannot combine "switch" with "is"'); + Assert(options.not === undefined, 'Cannot combine "switch" with "not"'); + Assert(options.then === undefined, 'Cannot combine "switch" with "then"'); - if (desc.override) { - return Common.symbols.override; - } + const rule = { + ref: exports.ref(condition), + switch: [], + break: options.break + }; - if (desc.ref) { - return Ref.build(desc.ref); - } + for (let i = 0; i < options.switch.length; ++i) { + const test = options.switch[i]; + const last = i === options.switch.length - 1; - if (desc.regex) { - return internals.regex(desc.regex); - } + Common.assertOptions(test, last ? ['is', 'then', 'otherwise'] : ['is', 'then']); - if (desc.special) { - Assert(['deep'].includes(desc.special), 'Unknown special value', desc.special); - return Common.symbols.deepDefault; - } + Assert(test.is !== undefined, 'Switch statement missing "is"'); + Assert(test.then !== undefined, 'Switch statement missing "then"'); - if (desc.value) { - return Clone(desc.value); - } - } + const item = { + is: schema.$_compile(test.is), + then: schema.$_compile(test.then) + }; - if (desc.type) { - return this.parse(desc); - } + if (!Ref.isRef(test.is) && + !Common.isSchema(test.is)) { - if (desc.template) { - return Template.build(desc); + item.is = item.is.required(); // Only apply required if this wasn't already a schema or a ref } - const normalized = {}; - for (const key in desc) { - normalized[key] = this.build(desc[key], { assign: key }); + if (last) { + Assert(options.otherwise === undefined || test.otherwise === undefined, 'Cannot specify "otherwise" inside and outside a "switch"'); + const otherwise = options.otherwise !== undefined ? options.otherwise : test.otherwise; + if (otherwise !== undefined) { + Assert(rule.break === undefined, 'Cannot specify both otherwise and break'); + item.otherwise = schema.$_compile(otherwise); + } } - return normalized; + rule.switch.push(item); } -}; - -internals.regex = function (string) { - - const end = string.lastIndexOf('/'); - const exp = string.slice(1, end); - const flags = string.slice(end + 1); - return new RegExp(exp, flags); + return rule; }; -internals.validate = function (joi, desc) { +internals.condition = function (schema, condition) { - Schemas = Schemas || __nccwpck_require__(85614); + for (const key of ['then', 'otherwise']) { + if (condition[key] === undefined) { + delete condition[key]; + } + else { + condition[key] = schema.$_compile(condition[key]); + } + } - joi.assert(desc, Schemas.description); + return condition; }; /***/ }), -/***/ 86103: +/***/ 69490: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); - -const Template = __nccwpck_require__(51396); - - -const internals = {}; - - -exports.compile = function (messages, target) { +const Annotate = __nccwpck_require__(46014); +const Common = __nccwpck_require__(72448); +const Template = __nccwpck_require__(51396); - // Single value string ('plain error message', 'template {error} message') - if (typeof messages === 'string') { - Assert(!target, 'Cannot set single message string'); - return new Template(messages); - } +const internals = {}; - // Single value template - if (Template.isTemplate(messages)) { - Assert(!target, 'Cannot set single message template'); - return messages; - } +exports.Report = class { - // By error code { 'number.min': } + constructor(code, value, local, flags, messages, state, prefs) { - Assert(typeof messages === 'object' && !Array.isArray(messages), 'Invalid message options'); + this.code = code; + this.flags = flags; + this.messages = messages; + this.path = state.path; + this.prefs = prefs; + this.state = state; + this.value = value; - target = target ? Clone(target) : {}; + this.message = null; + this.template = null; - for (let code in messages) { - const message = messages[code]; + this.local = local || {}; + this.local.label = exports.label(this.flags, this.state, this.prefs, this.messages); - if (code === 'root' || - Template.isTemplate(message)) { + if (this.value !== undefined && + !this.local.hasOwnProperty('value')) { - target[code] = message; - continue; + this.local.value = this.value; } - if (typeof message === 'string') { - target[code] = new Template(message); - continue; + if (this.path.length) { + const key = this.path[this.path.length - 1]; + if (typeof key !== 'object') { + this.local.key = key; + } } + } - // By language { english: { 'number.min': } } - - Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); - - const language = code; - target[language] = target[language] || {}; + _setTemplate(template) { - for (code in message) { - const localized = message[code]; + this.template = template; - if (code === 'root' || - Template.isTemplate(localized)) { + if (!this.flags.label && + this.path.length === 0) { - target[language][code] = localized; - continue; + const localized = this._template(this.template, 'root'); + if (localized) { + this.local.label = localized; } - - Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); - target[language][code] = new Template(localized); } } - return target; -}; + toString() { + if (this.message) { + return this.message; + } -exports.decompile = function (messages) { + const code = this.code; - // By error code { 'number.min': } + if (!this.prefs.errors.render) { + return this.code; + } - const target = {}; - for (let code in messages) { - const message = messages[code]; + const template = this._template(this.template) || + this._template(this.prefs.messages) || + this._template(this.messages); - if (code === 'root') { - target.root = message; - continue; + if (template === undefined) { + return `Error code "${code}" is not defined, your custom type is missing the correct messages definition`; } - if (Template.isTemplate(message)) { - target[code] = message.describe({ compact: true }); - continue; + // Render and cache result + + this.message = template.render(this.value, this.state, this.prefs, this.local, { errors: this.prefs.errors, messages: [this.prefs.messages, this.messages] }); + if (!this.prefs.errors.label) { + this.message = this.message.replace(/^"" /, '').trim(); } - // By language { english: { 'number.min': } } + return this.message; + } - const language = code; - target[language] = {}; + _template(messages, code) { - for (code in message) { - const localized = message[code]; + return exports.template(this.value, messages, code || this.code, this.state, this.prefs); + } +}; - if (code === 'root') { - target[language].root = localized; - continue; + +exports.path = function (path) { + + let label = ''; + for (const segment of path) { + if (typeof segment === 'object') { // Exclude array single path segment + continue; + } + + if (typeof segment === 'string') { + if (label) { + label += '.'; } - target[language][code] = localized.describe({ compact: true }); + label += segment; + } + else { + label += `[${segment}]`; } } - return target; + return label; }; -exports.merge = function (base, extended) { +exports.template = function (value, messages, code, state, prefs) { - if (!base) { - return exports.compile(extended); + if (!messages) { + return; } - if (!extended) { - return base; + if (Template.isTemplate(messages)) { + return code !== 'root' ? messages : null; } - // Single value string - - if (typeof extended === 'string') { - return new Template(extended); + let lang = prefs.errors.language; + if (Common.isResolvable(lang)) { + lang = lang.resolve(value, state, prefs); } - // Single value template + if (lang && + messages[lang]) { - if (Template.isTemplate(extended)) { - return extended; + if (messages[lang][code] !== undefined) { + return messages[lang][code]; + } + + if (messages[lang]['*'] !== undefined) { + return messages[lang]['*']; + } } - // By error code { 'number.min': } + if (!messages[code]) { + return messages['*']; + } - const target = Clone(base); + return messages[code]; +}; - for (let code in extended) { - const message = extended[code]; - if (code === 'root' || - Template.isTemplate(message)) { +exports.label = function (flags, state, prefs, messages) { - target[code] = message; - continue; - } + if (!prefs.errors.label) { + return ''; + } - if (typeof message === 'string') { - target[code] = new Template(message); - continue; - } + if (flags.label) { + return flags.label; + } - // By language { english: { 'number.min': } } + let path = state.path; + if (prefs.errors.label === 'key' && + state.path.length > 1) { - Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); + path = state.path.slice(-1); + } - const language = code; - target[language] = target[language] || {}; + const normalized = exports.path(path); + if (normalized) { + return normalized; + } - for (code in message) { - const localized = message[code]; + return exports.template(null, prefs.messages, 'root', state, prefs) || + messages && exports.template(null, messages, 'root', state, prefs) || + 'value'; +}; - if (code === 'root' || - Template.isTemplate(localized)) { - target[language][code] = localized; - continue; - } +exports.process = function (errors, original, prefs) { - Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); - target[language][code] = new Template(localized); - } + if (!errors) { + return null; } - return target; -}; + const { override, message, details } = exports.details(errors); + if (override) { + return override; + } + if (prefs.errors.stack) { + return new exports.ValidationError(message, details, original); + } -/***/ }), + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + const validationError = new exports.ValidationError(message, details, original); + Error.stackTraceLimit = limit; + return validationError; +}; -/***/ 81290: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +exports.details = function (errors, options = {}) { + + let messages = []; + const details = []; + for (const item of errors) { -const Assert = __nccwpck_require__(32718); + // Override -const Common = __nccwpck_require__(72448); -const Ref = __nccwpck_require__(73838); + if (item instanceof Error) { + if (options.override !== false) { + return { override: item }; + } + const message = item.toString(); + messages.push(message); -const internals = {}; + details.push({ + message, + type: 'override', + context: { error: item } + }); + continue; + } + // Report -exports.Ids = internals.Ids = class { + const message = item.toString(); + messages.push(message); - constructor() { + details.push({ + message, + path: item.path.filter((v) => typeof v !== 'object'), + type: item.code, + context: item.local + }); + } - this._byId = new Map(); - this._byKey = new Map(); - this._schemaChain = false; + if (messages.length > 1) { + messages = [...new Set(messages)]; } - clone() { + return { message: messages.join('. '), details }; +}; - const clone = new internals.Ids(); - clone._byId = new Map(this._byId); - clone._byKey = new Map(this._byKey); - clone._schemaChain = this._schemaChain; - return clone; - } - concat(source) { +exports.ValidationError = class extends Error { - if (source._schemaChain) { - this._schemaChain = true; - } + constructor(message, details, original) { - for (const [id, value] of source._byId.entries()) { - Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); - this._byId.set(id, value); - } + super(message); + this._original = original; + this.details = details; + } - for (const [key, value] of source._byKey.entries()) { - Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); - this._byKey.set(key, value); - } + static isError(err) { + + return err instanceof exports.ValidationError; } +}; - fork(path, adjuster, root) { - const chain = this._collect(path); - chain.push({ schema: root }); - const tail = chain.shift(); - let adjusted = { id: tail.id, schema: adjuster(tail.schema) }; +exports.ValidationError.prototype.isJoi = true; - Assert(Common.isSchema(adjusted.schema), 'adjuster function failed to return a joi schema type'); +exports.ValidationError.prototype.name = 'ValidationError'; - for (const node of chain) { - adjusted = { id: node.id, schema: internals.fork(node.schema, adjusted.id, adjusted.schema) }; - } +exports.ValidationError.prototype.annotate = Annotate.error; - return adjusted.schema; - } - labels(path, behind = []) { +/***/ }), - const current = path[0]; - const node = this._get(current); - if (!node) { - return [...behind, ...path].join('.'); - } +/***/ 86680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const forward = path.slice(1); - behind = [...behind, node.schema._flags.label || current]; - if (!forward.length) { - return behind.join('.'); - } +"use strict"; - return node.schema._ids.labels(forward, behind); - } - reach(path, behind = []) { +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); - const current = path[0]; - const node = this._get(current); - Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); - const forward = path.slice(1); - if (!forward.length) { - return node.schema; - } - return node.schema._ids.reach(forward, [...behind, current]); - } +const internals = {}; - register(schema, { key } = {}) { - if (!schema || - !Common.isSchema(schema)) { +exports.type = function (from, options) { - return; - } + const base = Object.getPrototypeOf(from); + const prototype = Clone(base); + const schema = from._assign(Object.create(prototype)); + const def = Object.assign({}, options); // Shallow cloned + delete def.base; - if (schema.$_property('schemaChain') || - schema._ids._schemaChain) { + prototype._definition = def; - this._schemaChain = true; - } + const parent = base._definition || {}; + def.messages = Messages.merge(parent.messages, def.messages); + def.properties = Object.assign({}, parent.properties, def.properties); - const id = schema._flags.id; - if (id) { - const existing = this._byId.get(id); - Assert(!existing || existing.schema === schema, 'Cannot add different schemas with the same id:', id); - Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); + // Type - this._byId.set(id, { schema, id }); - } + schema.type = def.type; - if (key) { - Assert(!this._byKey.has(key), 'Schema already contains key:', key); - Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); + // Flags - this._byKey.set(key, { schema, id: key }); + def.flags = Object.assign({}, parent.flags, def.flags); + + // Terms + + const terms = Object.assign({}, parent.terms); + if (def.terms) { + for (const name in def.terms) { // Only apply own terms + const term = def.terms[name]; + Assert(schema.$_terms[name] === undefined, 'Invalid term override for', def.type, name); + schema.$_terms[name] = term.init; + terms[name] = term; } } - reset() { + def.terms = terms; - this._byId = new Map(); - this._byKey = new Map(); - this._schemaChain = false; + // Constructor arguments + + if (!def.args) { + def.args = parent.args; } - _collect(path, behind = [], nodes = []) { + // Prepare - const current = path[0]; - const node = this._get(current); - Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); + def.prepare = internals.prepare(def.prepare, parent.prepare); - nodes = [node, ...nodes]; + // Coerce - const forward = path.slice(1); - if (!forward.length) { - return nodes; + if (def.coerce) { + if (typeof def.coerce === 'function') { + def.coerce = { method: def.coerce }; } - return node.schema._ids._collect(forward, [...behind, current], nodes); - } - - _get(id) { + if (def.coerce.from && + !Array.isArray(def.coerce.from)) { - return this._byId.get(id) || this._byKey.get(id); + def.coerce = { method: def.coerce.method, from: [].concat(def.coerce.from) }; + } } -}; + def.coerce = internals.coerce(def.coerce, parent.coerce); -internals.fork = function (schema, id, replacement) { + // Validate - const each = (item, { key }) => { + def.validate = internals.validate(def.validate, parent.validate); - if (id === (item._flags.id || key)) { - return replacement; - } - }; + // Rules - const obj = exports.schema(schema, { each, ref: false }); - return obj ? obj.$_mutateRebuild() : schema; -}; + const rules = Object.assign({}, parent.rules); + if (def.rules) { + for (const name in def.rules) { + const rule = def.rules[name]; + Assert(typeof rule === 'object', 'Invalid rule definition for', def.type, name); + let method = rule.method; + if (method === undefined) { + method = function () { -exports.schema = function (schema, options) { + return this.$_addRule(name); + }; + } - let obj; + if (method) { + Assert(!prototype[name], 'Rule conflict in', def.type, name); + prototype[name] = method; + } - for (const name in schema._flags) { - if (name[0] === '_') { - continue; - } + Assert(!rules[name], 'Rule conflict in', def.type, name); + rules[name] = rule; - const result = internals.scan(schema._flags[name], { source: 'flags', name }, options); - if (result !== undefined) { - obj = obj || schema.clone(); - obj._flags[name] = result; - } - } + if (rule.alias) { + const aliases = [].concat(rule.alias); + for (const alias of aliases) { + prototype[alias] = rule.method; + } + } - for (let i = 0; i < schema._rules.length; ++i) { - const rule = schema._rules[i]; - const result = internals.scan(rule.args, { source: 'rules', name: rule.name }, options); - if (result !== undefined) { - obj = obj || schema.clone(); - const clone = Object.assign({}, rule); - clone.args = result; - obj._rules[i] = clone; + if (rule.args) { + rule.argsByName = new Map(); + rule.args = rule.args.map((arg) => { - const existingUnique = obj._singleRules.get(rule.name); - if (existingUnique === rule) { - obj._singleRules.set(rule.name, clone); - } - } - } + if (typeof arg === 'string') { + arg = { name: arg }; + } - for (const name in schema.$_terms) { - if (name[0] === '_') { - continue; - } + Assert(!rule.argsByName.has(arg.name), 'Duplicated argument name', arg.name); - const result = internals.scan(schema.$_terms[name], { source: 'terms', name }, options); - if (result !== undefined) { - obj = obj || schema.clone(); - obj.$_terms[name] = result; + if (Common.isSchema(arg.assert)) { + arg.assert = arg.assert.strict().label(arg.name); + } + + rule.argsByName.set(arg.name, arg); + return arg; + }); + } } } - return obj; -}; - + def.rules = rules; -internals.scan = function (item, source, options, _path, _key) { + // Modifiers - const path = _path || []; + const modifiers = Object.assign({}, parent.modifiers); + if (def.modifiers) { + for (const name in def.modifiers) { + Assert(!prototype[name], 'Rule conflict in', def.type, name); - if (item === null || - typeof item !== 'object') { + const modifier = def.modifiers[name]; + Assert(typeof modifier === 'function', 'Invalid modifier definition for', def.type, name); - return; - } + const method = function (arg) { - let clone; + return this.rule({ [name]: arg }); + }; - if (Array.isArray(item)) { - for (let i = 0; i < item.length; ++i) { - const key = source.source === 'terms' && source.name === 'keys' && item[i].key; - const result = internals.scan(item[i], source, options, [i, ...path], key); - if (result !== undefined) { - clone = clone || item.slice(); - clone[i] = result; - } + prototype[name] = method; + modifiers[name] = modifier; } - - return clone; } - if (options.schema !== false && Common.isSchema(item) || - options.ref !== false && Ref.isRef(item)) { - - const result = options.each(item, { ...source, path, key: _key }); - if (result === item) { - return; - } + def.modifiers = modifiers; - return result; - } + // Overrides - for (const key in item) { - if (key[0] === '_') { - continue; + if (def.overrides) { + prototype._super = base; + schema.$_super = {}; // Backwards compatibility + for (const override in def.overrides) { + Assert(base[override], 'Cannot override missing', override); + def.overrides[override][Common.symbols.parent] = base[override]; + schema.$_super[override] = base[override].bind(schema); // Backwards compatibility } - const result = internals.scan(item[key], source, options, [key, ...path], _key); - if (result !== undefined) { - clone = clone || Object.assign({}, item); - clone[key] = result; - } + Object.assign(prototype, def.overrides); } - return clone; -}; + // Casts + def.cast = Object.assign({}, parent.cast, def.cast); -/***/ }), + // Manifest -/***/ 73838: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const manifest = Object.assign({}, parent.manifest, def.manifest); + manifest.build = internals.build(def.manifest && def.manifest.build, parent.manifest && parent.manifest.build); + def.manifest = manifest; -"use strict"; + // Rebuild + def.rebuild = internals.rebuild(def.rebuild, parent.rebuild); -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Reach = __nccwpck_require__(18891); + return schema; +}; -const Common = __nccwpck_require__(72448); -let Template; +// Helpers +internals.build = function (child, parent) { -const internals = { - symbol: Symbol('ref'), // Used to internally identify references (shared with other joi versions) - defaults: { - adjust: null, - in: false, - iterables: null, - map: null, - separator: '.', - type: 'value' + if (!child || + !parent) { + + return child || parent; } + + return function (obj, desc) { + + return parent(child(obj, desc), desc); + }; }; -exports.create = function (key, options = {}) { +internals.coerce = function (child, parent) { - Assert(typeof key === 'string', 'Invalid reference key:', key); - Common.assertOptions(options, ['adjust', 'ancestor', 'in', 'iterables', 'map', 'prefix', 'render', 'separator']); - Assert(!options.prefix || typeof options.prefix === 'object', 'options.prefix must be of type object'); + if (!child || + !parent) { - const ref = Object.assign({}, internals.defaults, options); - delete ref.prefix; + return child || parent; + } - const separator = ref.separator; - const context = internals.context(key, separator, options.prefix); - ref.type = context.type; - key = context.key; + return { + from: child.from && parent.from ? [...new Set([...child.from, ...parent.from])] : null, + method(value, helpers) { - if (ref.type === 'value') { - if (context.root) { - Assert(!separator || key[0] !== separator, 'Cannot specify relative path with root prefix'); - ref.ancestor = 'root'; - if (!key) { - key = null; - } - } + let coerced; + if (!parent.from || + parent.from.includes(typeof value)) { - if (separator && - separator === key) { + coerced = parent.method(value, helpers); + if (coerced) { + if (coerced.errors || + coerced.value === undefined) { - key = null; - ref.ancestor = 0; - } - else { - if (ref.ancestor !== undefined) { - Assert(!separator || !key || key[0] !== separator, 'Cannot combine prefix with ancestor option'); - } - else { - const [ancestor, slice] = internals.ancestor(key, separator); - if (slice) { - key = key.slice(slice); - if (key === '') { - key = null; + return coerced; } + + value = coerced.value; } + } - ref.ancestor = ancestor; + if (!child.from || + child.from.includes(typeof value)) { + + const own = child.method(value, helpers); + if (own) { + return own; + } } + + return coerced; } - } + }; +}; - ref.path = separator ? (key === null ? [] : key.split(separator)) : [key]; - return new internals.Ref(ref); -}; +internals.prepare = function (child, parent) { + if (!child || + !parent) { -exports["in"] = function (key, options = {}) { + return child || parent; + } - return exports.create(key, { ...options, in: true }); -}; + return function (value, helpers) { + const prepared = child(value, helpers); + if (prepared) { + if (prepared.errors || + prepared.value === undefined) { -exports.isRef = function (ref) { + return prepared; + } - return ref ? !!ref[Common.symbols.ref] : false; + value = prepared.value; + } + + return parent(value, helpers) || prepared; + }; }; -internals.Ref = class { +internals.rebuild = function (child, parent) { - constructor(options) { + if (!child || + !parent) { - Assert(typeof options === 'object', 'Invalid reference construction'); - Common.assertOptions(options, [ - 'adjust', 'ancestor', 'in', 'iterables', 'map', 'path', 'render', 'separator', 'type', // Copied - 'depth', 'key', 'root', 'display' // Overridden - ]); + return child || parent; + } - Assert([false, undefined].includes(options.separator) || typeof options.separator === 'string' && options.separator.length === 1, 'Invalid separator'); - Assert(!options.adjust || typeof options.adjust === 'function', 'options.adjust must be a function'); - Assert(!options.map || Array.isArray(options.map), 'options.map must be an array'); - Assert(!options.map || !options.adjust, 'Cannot set both map and adjust options'); + return function (schema) { - Object.assign(this, internals.defaults, options); + parent(schema); + child(schema); + }; +}; - Assert(this.type === 'value' || this.ancestor === undefined, 'Non-value references cannot reference ancestors'); - if (Array.isArray(this.map)) { - this.map = new Map(this.map); - } +internals.validate = function (child, parent) { - this.depth = this.path.length; - this.key = this.path.length ? this.path.join(this.separator) : null; - this.root = this.path[0]; + if (!child || + !parent) { - this.updateDisplay(); + return child || parent; } - resolve(value, state, prefs, local, options = {}) { - - Assert(!this.in || options.in, 'Invalid in() reference usage'); + return function (value, helpers) { - if (this.type === 'global') { - return this._resolve(prefs.context, state, options); - } + const result = parent(value, helpers); + if (result) { + if (result.errors && + (!Array.isArray(result.errors) || result.errors.length)) { - if (this.type === 'local') { - return this._resolve(local, state, options); - } + return result; + } - if (!this.ancestor) { - return this._resolve(value, state, options); + value = result.value; } - if (this.ancestor === 'root') { - return this._resolve(state.ancestors[state.ancestors.length - 1], state, options); - } + return child(value, helpers) || result; + }; +}; - Assert(this.ancestor <= state.ancestors.length, 'Invalid reference exceeds the schema root:', this.display); - return this._resolve(state.ancestors[this.ancestor - 1], state, options); - } - _resolve(target, state, options) { +/***/ }), - let resolved; +/***/ 20918: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.type === 'value' && - state.mainstay.shadow && - options.shadow !== false) { +"use strict"; - resolved = state.mainstay.shadow.get(this.absolute(state)); - } - if (resolved === undefined) { - resolved = Reach(target, this.path, { iterables: this.iterables, functions: true }); - } +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); - if (this.adjust) { - resolved = this.adjust(resolved); - } +const Cache = __nccwpck_require__(63355); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Extend = __nccwpck_require__(86680); +const Manifest = __nccwpck_require__(87997); +const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); +const Trace = __nccwpck_require__(43171); - if (this.map) { - const mapped = this.map.get(resolved); - if (mapped !== undefined) { - resolved = mapped; - } - } +let Schemas; - if (state.mainstay) { - state.mainstay.tracer.resolve(state, this, resolved); - } - return resolved; +const internals = { + types: { + alternatives: __nccwpck_require__(26867), + any: __nccwpck_require__(9512), + array: __nccwpck_require__(20270), + boolean: __nccwpck_require__(47489), + date: __nccwpck_require__(6624), + function: __nccwpck_require__(62269), + link: __nccwpck_require__(69869), + number: __nccwpck_require__(15855), + object: __nccwpck_require__(46878), + string: __nccwpck_require__(72260), + symbol: __nccwpck_require__(40971) + }, + aliases: { + alt: 'alternatives', + bool: 'boolean', + func: 'function' } +}; - toString() { - return this.display; - } +if (Buffer) { // $lab:coverage:ignore$ + internals.types.binary = __nccwpck_require__(34288); +} - absolute(state) { - return [...state.path.slice(0, -this.ancestor), ...this.path]; - } +internals.root = function () { - clone() { + const root = { + _types: new Set(Object.keys(internals.types)) + }; - return new internals.Ref(this); - } + // Types - describe() { + for (const type of root._types) { + root[type] = function (...args) { - const ref = { path: this.path }; + Assert(!args.length || ['alternatives', 'link', 'object'].includes(type), 'The', type, 'type does not allow arguments'); + return internals.generate(this, internals.types[type], args); + }; + } - if (this.type !== 'value') { - ref.type = this.type; - } + // Shortcuts - if (this.separator !== '.') { - ref.separator = this.separator; - } + for (const method of ['allow', 'custom', 'disallow', 'equal', 'exist', 'forbidden', 'invalid', 'not', 'only', 'optional', 'options', 'prefs', 'preferences', 'required', 'strip', 'valid', 'when']) { + root[method] = function (...args) { - if (this.type === 'value' && - this.ancestor !== 1) { + return this.any()[method](...args); + }; + } - ref.ancestor = this.ancestor; - } + // Methods - if (this.map) { - ref.map = [...this.map]; - } + Object.assign(root, internals.methods); - for (const key of ['adjust', 'iterables', 'render']) { - if (this[key] !== null && - this[key] !== undefined) { + // Aliases - ref[key] = this[key]; - } - } + for (const alias in internals.aliases) { + const target = internals.aliases[alias]; + root[alias] = root[target]; + } - if (this.in !== false) { - ref.in = true; - } + root.x = root.expression; - return { ref }; + // Trace + + if (Trace.setup) { // $lab:coverage:ignore$ + Trace.setup(root); } - updateDisplay() { + return root; +}; - const key = this.key !== null ? this.key : ''; - if (this.type !== 'value') { - this.display = `ref:${this.type}:${key}`; - return; - } - if (!this.separator) { - this.display = `ref:${key}`; - return; - } +internals.methods = { - if (!this.ancestor) { - this.display = `ref:${this.separator}${key}`; - return; - } + ValidationError: Errors.ValidationError, + version: Common.version, + cache: Cache.provider, - if (this.ancestor === 'root') { - this.display = `ref:root:${key}`; - return; - } + assert(value, schema, ...args /* [message], [options] */) { - if (this.ancestor === 1) { - this.display = `ref:${key || '..'}`; - return; - } + internals.assert(value, schema, true, args); + }, - const lead = new Array(this.ancestor + 1).fill(this.separator).join(''); - this.display = `ref:${lead}${key || ''}`; - } -}; + attempt(value, schema, ...args /* [message], [options] */) { + return internals.assert(value, schema, false, args); + }, -internals.Ref.prototype[Common.symbols.ref] = true; + build(desc) { + Assert(typeof Manifest.build === 'function', 'Manifest functionality disabled'); + return Manifest.build(this, desc); + }, -exports.build = function (desc) { + checkPreferences(prefs) { - desc = Object.assign({}, internals.defaults, desc); - if (desc.type === 'value' && - desc.ancestor === undefined) { + Common.checkPreferences(prefs); + }, - desc.ancestor = 1; - } + compile(schema, options) { - return new internals.Ref(desc); -}; + return Compile.compile(this, schema, options); + }, + defaults(modifier) { -internals.context = function (key, separator, prefix = {}) { + Assert(typeof modifier === 'function', 'modifier must be a function'); - key = key.trim(); + const joi = Object.assign({}, this); + for (const type of joi._types) { + const schema = modifier(joi[type]()); + Assert(Common.isSchema(schema), 'modifier must return a valid schema object'); - if (prefix) { - const globalp = prefix.global === undefined ? '$' : prefix.global; - if (globalp !== separator && - key.startsWith(globalp)) { + joi[type] = function (...args) { - return { key: key.slice(globalp.length), type: 'global' }; + return internals.generate(this, schema, args); + }; } - const local = prefix.local === undefined ? '#' : prefix.local; - if (local !== separator && - key.startsWith(local)) { + return joi; + }, - return { key: key.slice(local.length), type: 'local' }; - } + expression(...args) { - const root = prefix.root === undefined ? '/' : prefix.root; - if (root !== separator && - key.startsWith(root)) { + return new Template(...args); + }, - return { key: key.slice(root.length), type: 'value', root: true }; - } - } + extend(...extensions) { - return { key, type: 'value' }; -}; + Common.verifyFlat(extensions, 'extend'); + Schemas = Schemas || __nccwpck_require__(85614); -internals.ancestor = function (key, separator) { + Assert(extensions.length, 'You need to provide at least one extension'); + this.assert(extensions, Schemas.extensions); - if (!separator) { - return [1, 0]; // 'a_b' -> 1 (parent) - } + const joi = Object.assign({}, this); + joi._types = new Set(joi._types); - if (key[0] !== separator) { // 'a.b' -> 1 (parent) - return [1, 0]; - } + for (let extension of extensions) { + if (typeof extension === 'function') { + extension = extension(joi); + } - if (key[1] !== separator) { // '.a.b' -> 0 (self) - return [0, 1]; - } + this.assert(extension, Schemas.extension); - let i = 2; - while (key[i] === separator) { - ++i; - } + const expanded = internals.expandExtension(extension, joi); + for (const item of expanded) { + Assert(joi[item.type] === undefined || joi._types.has(item.type), 'Cannot override name', item.type); + + const base = item.base || this.any(); + const schema = Extend.type(base, item); + + joi._types.add(item.type); + joi[item.type] = function (...args) { + + return internals.generate(this, schema, args); + }; + } + } - return [i - 1, i]; // '...a.b.' -> 2 (grandparent) -}; + return joi; + }, + isError: Errors.ValidationError.isError, + isExpression: Template.isTemplate, + isRef: Ref.isRef, + isSchema: Common.isSchema, -exports.toSibling = 0; + in(...args) { -exports.toParent = 1; + return Ref.in(...args); + }, + override: Common.symbols.override, -exports.Manager = class { + ref(...args) { - constructor() { + return Ref.create(...args); + }, - this.refs = []; // 0: [self refs], 1: [parent refs], 2: [grandparent refs], ... - } + types() { - register(source, target) { + const types = {}; + for (const type of this._types) { + types[type] = this[type](); + } - if (!source) { - return; + for (const target in internals.aliases) { + types[target] = this[target](); } - target = target === undefined ? exports.toParent : target; + return types; + } +}; - // Array - if (Array.isArray(source)) { - for (const ref of source) { - this.register(ref, target); - } +// Helpers - return; - } +internals.assert = function (value, schema, annotate, args /* [message], [options] */) { - // Schema + const message = args[0] instanceof Error || typeof args[0] === 'string' ? args[0] : null; + const options = message !== null ? args[1] : args[0]; + const result = schema.validate(value, Common.preferences({ errors: { stack: true } }, options || {})); - if (Common.isSchema(source)) { - for (const item of source._refs.refs) { - if (item.ancestor - target >= 0) { - this.refs.push({ ancestor: item.ancestor - target, root: item.root }); - } - } + let error = result.error; + if (!error) { + return result.value; + } - return; - } + if (message instanceof Error) { + throw message; + } - // Reference + const display = annotate && typeof error.annotate === 'function' ? error.annotate() : error.message; - if (exports.isRef(source) && - source.type === 'value' && - source.ancestor - target >= 0) { + if (error instanceof Errors.ValidationError === false) { + error = Clone(error); + } - this.refs.push({ ancestor: source.ancestor - target, root: source.root }); - } + error.message = message ? `${message} ${display}` : display; + throw error; +}; - // Template - Template = Template || __nccwpck_require__(51396); +internals.generate = function (root, schema, args) { - if (Template.isTemplate(source)) { - this.register(source.refs(), target); - } - } + Assert(root, 'Must be invoked on a Joi instance.'); - get length() { + schema.$_root = root; - return this.refs.length; + if (!schema._definition.args || + !args.length) { + + return schema; } - clone() { + return schema._definition.args(schema, ...args); +}; - const copy = new exports.Manager(); - copy.refs = Clone(this.refs); - return copy; - } - reset() { +internals.expandExtension = function (extension, joi) { - this.refs = []; + if (typeof extension.type === 'string') { + return [extension]; } - roots() { - - return this.refs.filter((ref) => !ref.ancestor).map((ref) => ref.root); + const extended = []; + for (const type of joi._types) { + if (extension.type.test(type)) { + const item = Object.assign({}, extension); + item.type = type; + item.base = joi[type](); + extended.push(item); + } } + + return extended; }; +module.exports = internals.root(); + + /***/ }), -/***/ 85614: +/***/ 87997: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const Joi = __nccwpck_require__(20918); - - -const internals = {}; +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); +const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); -// Preferences +let Schemas; -internals.wrap = Joi.string() - .min(1) - .max(2) - .allow(false); +const internals = {}; -exports.preferences = Joi.object({ - allowUnknown: Joi.boolean(), - abortEarly: Joi.boolean(), - artifacts: Joi.boolean(), - cache: Joi.boolean(), - context: Joi.object(), - convert: Joi.boolean(), - dateFormat: Joi.valid('date', 'iso', 'string', 'time', 'utc'), - debug: Joi.boolean(), - errors: { - escapeHtml: Joi.boolean(), - label: Joi.valid('path', 'key', false), - language: [ - Joi.string(), - Joi.object().ref() - ], - render: Joi.boolean(), - stack: Joi.boolean(), - wrap: { - label: internals.wrap, - array: internals.wrap, - string: internals.wrap - } - }, - externals: Joi.boolean(), - messages: Joi.object(), - noDefaults: Joi.boolean(), - nonEnumerables: Joi.boolean(), - presence: Joi.valid('required', 'optional', 'forbidden'), - skipFunctions: Joi.boolean(), - stripUnknown: Joi.object({ - arrays: Joi.boolean(), - objects: Joi.boolean() - }) - .or('arrays', 'objects') - .allow(true, false), - warnings: Joi.boolean() -}) - .strict(); +exports.describe = function (schema) { -// Extensions + const def = schema._definition; -internals.nameRx = /^[a-zA-Z0-9]\w*$/; + // Type + const desc = { + type: schema.type, + flags: {}, + rules: [] + }; -internals.rule = Joi.object({ - alias: Joi.array().items(Joi.string().pattern(internals.nameRx)).single(), - args: Joi.array().items( - Joi.string(), - Joi.object({ - name: Joi.string().pattern(internals.nameRx).required(), - ref: Joi.boolean(), - assert: Joi.alternatives([ - Joi.function(), - Joi.object().schema() - ]) - .conditional('ref', { is: true, then: Joi.required() }), - normalize: Joi.function(), - message: Joi.string().when('assert', { is: Joi.function(), then: Joi.required() }) - }) - ), - convert: Joi.boolean(), - manifest: Joi.boolean(), - method: Joi.function().allow(false), - multi: Joi.boolean(), - validate: Joi.function() -}); + // Flags + for (const flag in schema._flags) { + if (flag[0] !== '_') { + desc.flags[flag] = internals.describe(schema._flags[flag]); + } + } -exports.extension = Joi.object({ - type: Joi.alternatives([ - Joi.string(), - Joi.object().regex() - ]) - .required(), - args: Joi.function(), - cast: Joi.object().pattern(internals.nameRx, Joi.object({ - from: Joi.function().maxArity(1).required(), - to: Joi.function().minArity(1).maxArity(2).required() - })), - base: Joi.object().schema() - .when('type', { is: Joi.object().regex(), then: Joi.forbidden() }), - coerce: [ - Joi.function().maxArity(3), - Joi.object({ method: Joi.function().maxArity(3).required(), from: Joi.array().items(Joi.string()).single() }) - ], - flags: Joi.object().pattern(internals.nameRx, Joi.object({ - setter: Joi.string(), - default: Joi.any() - })), - manifest: { - build: Joi.function().arity(2) - }, - messages: [Joi.object(), Joi.string()], - modifiers: Joi.object().pattern(internals.nameRx, Joi.function().minArity(1).maxArity(2)), - overrides: Joi.object().pattern(internals.nameRx, Joi.function()), - prepare: Joi.function().maxArity(3), - rebuild: Joi.function().arity(1), - rules: Joi.object().pattern(internals.nameRx, internals.rule), - terms: Joi.object().pattern(internals.nameRx, Joi.object({ - init: Joi.array().allow(null).required(), - manifest: Joi.object().pattern(/.+/, [ - Joi.valid('schema', 'single'), - Joi.object({ - mapped: Joi.object({ - from: Joi.string().required(), - to: Joi.string().required() - }) - .required() - }) - ]) - })), - validate: Joi.function().maxArity(3) -}) - .strict(); + if (!Object.keys(desc.flags).length) { + delete desc.flags; + } + // Preferences -exports.extensions = Joi.array().items(Joi.object(), Joi.function().arity(1)).strict(); + if (schema._preferences) { + desc.preferences = Clone(schema._preferences, { shallow: ['messages'] }); + delete desc.preferences[Common.symbols.prefs]; + if (desc.preferences.messages) { + desc.preferences.messages = Messages.decompile(desc.preferences.messages); + } + } + // Allow / Invalid -// Manifest + if (schema._valids) { + desc.allow = schema._valids.describe(); + } -internals.desc = { + if (schema._invalids) { + desc.invalid = schema._invalids.describe(); + } - buffer: Joi.object({ - buffer: Joi.string() - }), + // Rules - func: Joi.object({ - function: Joi.function().required(), - options: { - literal: true + for (const rule of schema._rules) { + const ruleDef = def.rules[rule.name]; + if (ruleDef.manifest === false) { // Defaults to true + continue; } - }), - override: Joi.object({ - override: true - }), - - ref: Joi.object({ - ref: Joi.object({ - type: Joi.valid('value', 'global', 'local'), - path: Joi.array().required(), - separator: Joi.string().length(1).allow(false), - ancestor: Joi.number().min(0).integer().allow('root'), - map: Joi.array().items(Joi.array().length(2)).min(1), - adjust: Joi.function(), - iterables: Joi.boolean(), - in: Joi.boolean(), - render: Joi.boolean() - }) - .required() - }), + const item = { name: rule.name }; - regex: Joi.object({ - regex: Joi.string().min(3) - }), + for (const custom in def.modifiers) { + if (rule[custom] !== undefined) { + item[custom] = internals.describe(rule[custom]); + } + } - special: Joi.object({ - special: Joi.valid('deep').required() - }), + if (rule.args) { + item.args = {}; + for (const key in rule.args) { + const arg = rule.args[key]; + if (key === 'options' && + !Object.keys(arg).length) { - template: Joi.object({ - template: Joi.string().required(), - options: Joi.object() - }), + continue; + } - value: Joi.object({ - value: Joi.alternatives([Joi.object(), Joi.array()]).required() - }) -}; + item.args[key] = internals.describe(arg, { assign: key }); + } + if (!Object.keys(item.args).length) { + delete item.args; + } + } -internals.desc.entity = Joi.alternatives([ - Joi.array().items(Joi.link('...')), - Joi.boolean(), - Joi.function(), - Joi.number(), - Joi.string(), - internals.desc.buffer, - internals.desc.func, - internals.desc.ref, - internals.desc.regex, - internals.desc.special, - internals.desc.template, - internals.desc.value, - Joi.link('/') -]); + desc.rules.push(item); + } + if (!desc.rules.length) { + delete desc.rules; + } -internals.desc.values = Joi.array() - .items( - null, - Joi.boolean(), - Joi.function(), - Joi.number().allow(Infinity, -Infinity), - Joi.string().allow(''), - Joi.symbol(), - internals.desc.buffer, - internals.desc.func, - internals.desc.override, - internals.desc.ref, - internals.desc.regex, - internals.desc.template, - internals.desc.value - ); + // Terms (must be last to verify no name conflicts) + for (const term in schema.$_terms) { + if (term[0] === '_') { + continue; + } -internals.desc.messages = Joi.object() - .pattern(/.+/, [ - Joi.string(), - internals.desc.template, - Joi.object().pattern(/.+/, [Joi.string(), internals.desc.template]) - ]); + Assert(!desc[term], 'Cannot describe schema due to internal name conflict with', term); + const items = schema.$_terms[term]; + if (!items) { + continue; + } -exports.description = Joi.object({ - type: Joi.string().required(), - flags: Joi.object({ - cast: Joi.string(), - default: Joi.any(), - description: Joi.string(), - empty: Joi.link('/'), - failover: internals.desc.entity, - id: Joi.string(), - label: Joi.string(), - only: true, - presence: ['optional', 'required', 'forbidden'], - result: ['raw', 'strip'], - strip: Joi.boolean(), - unit: Joi.string() - }) - .unknown(), - preferences: { - allowUnknown: Joi.boolean(), - abortEarly: Joi.boolean(), - artifacts: Joi.boolean(), - cache: Joi.boolean(), - convert: Joi.boolean(), - dateFormat: ['date', 'iso', 'string', 'time', 'utc'], - errors: { - escapeHtml: Joi.boolean(), - label: ['path', 'key'], - language: [ - Joi.string(), - internals.desc.ref - ], - wrap: { - label: internals.wrap, - array: internals.wrap + if (items instanceof Map) { + if (items.size) { + desc[term] = [...items.entries()]; } - }, - externals: Joi.boolean(), - messages: internals.desc.messages, - noDefaults: Joi.boolean(), - nonEnumerables: Joi.boolean(), - presence: ['required', 'optional', 'forbidden'], - skipFunctions: Joi.boolean(), - stripUnknown: Joi.object({ - arrays: Joi.boolean(), - objects: Joi.boolean() - }) - .or('arrays', 'objects') - .allow(true, false), - warnings: Joi.boolean() - }, - allow: internals.desc.values, - invalid: internals.desc.values, - rules: Joi.array().min(1).items({ - name: Joi.string().required(), - args: Joi.object().min(1), - keep: Joi.boolean(), - message: [ - Joi.string(), - internals.desc.messages - ], - warn: Joi.boolean() - }), - // Terms - - keys: Joi.object().pattern(/.*/, Joi.link('/')), - link: internals.desc.ref -}) - .pattern(/^[a-z]\w*$/, Joi.any()); - - -/***/ }), - -/***/ 73634: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + continue; + } -"use strict"; + if (Common.isValues(items)) { + desc[term] = items.describe(); + continue; + } + Assert(def.terms[term], 'Term', term, 'missing configuration'); + const manifest = def.terms[term].manifest; + const mapped = typeof manifest === 'object'; + if (!items.length && + !mapped) { -const Clone = __nccwpck_require__(85578); -const Reach = __nccwpck_require__(18891); + continue; + } -const Common = __nccwpck_require__(72448); + const normalized = []; + for (const item of items) { + normalized.push(internals.describe(item)); + } + // Mapped -const internals = { - value: Symbol('value') -}; + if (mapped) { + const { from, to } = manifest.mapped; + desc[term] = {}; + for (const item of normalized) { + desc[term][item[to]] = item[from]; + } + continue; + } -module.exports = internals.State = class { + // Single - constructor(path, ancestors, state) { + if (manifest === 'single') { + Assert(normalized.length === 1, 'Term', term, 'contains more than one item'); + desc[term] = normalized[0]; + continue; + } - this.path = path; - this.ancestors = ancestors; // [parent, ..., root] + // Array - this.mainstay = state.mainstay; - this.schemas = state.schemas; // [current, ..., root] - this.debug = null; + desc[term] = normalized; } - localize(path, ancestors = null, schema = null) { + internals.validate(schema.$_root, desc); + return desc; +}; - const state = new internals.State(path, ancestors, this); - if (schema && - state.schemas) { +internals.describe = function (item, options = {}) { - state.schemas = [internals.schemas(schema), ...state.schemas]; - } + if (Array.isArray(item)) { + return item.map(internals.describe); + } - return state; + if (item === Common.symbols.deepDefault) { + return { special: 'deep' }; } - nest(schema, debug) { + if (typeof item !== 'object' || + item === null) { - const state = new internals.State(this.path, this.ancestors, this); - state.schemas = state.schemas && [internals.schemas(schema), ...state.schemas]; - state.debug = debug; - return state; + return item; } - shadow(value, reason) { + if (options.assign === 'options') { + return Clone(item); + } - this.mainstay.shadow = this.mainstay.shadow || new internals.Shadow(); - this.mainstay.shadow.set(this.path, value, reason); + if (Buffer && Buffer.isBuffer(item)) { // $lab:coverage:ignore$ + return { buffer: item.toString('binary') }; } - snapshot() { + if (item instanceof Date) { + return item.toISOString(); + } - if (this.mainstay.shadow) { - this._snapshot = Clone(this.mainstay.shadow.node(this.path)); + if (item instanceof Error) { + return item; + } + + if (item instanceof RegExp) { + if (options.assign === 'regex') { + return item.toString(); } - this.mainstay.snapshot(); + return { regex: item.toString() }; } - restore() { + if (item[Common.symbols.literal]) { + return { function: item.literal }; + } - if (this.mainstay.shadow) { - this.mainstay.shadow.override(this.path, this._snapshot); - this._snapshot = undefined; + if (typeof item.describe === 'function') { + if (options.assign === 'ref') { + return item.describe().ref; } - this.mainstay.restore(); + return item.describe(); } - commit() { - - if (this.mainstay.shadow) { - this.mainstay.shadow.override(this.path, this._snapshot); - this._snapshot = undefined; + const normalized = {}; + for (const key in item) { + const value = item[key]; + if (value === undefined) { + continue; } - this.mainstay.commit(); + normalized[key] = internals.describe(value, { assign: key }); } -}; + return normalized; +}; -internals.schemas = function (schema) { - if (Common.isSchema(schema)) { - return { schema }; - } +exports.build = function (joi, desc) { - return schema; + const builder = new internals.Builder(joi); + return builder.parse(desc); }; -internals.Shadow = class { +internals.Builder = class { - constructor() { + constructor(joi) { - this._values = null; + this.joi = joi; } - set(path, value, reason) { + parse(desc) { - if (!path.length) { // No need to store root value - return; - } + internals.validate(this.joi, desc); - if (reason === 'strip' && - typeof path[path.length - 1] === 'number') { // Cannot store stripped array values (due to shift) + // Type - return; - } + let schema = this.joi[desc.type]()._bare(); + const def = schema._definition; - this._values = this._values || new Map(); + // Flags - let node = this._values; - for (let i = 0; i < path.length; ++i) { - const segment = path[i]; - let next = node.get(segment); - if (!next) { - next = new Map(); - node.set(segment, next); + if (desc.flags) { + for (const flag in desc.flags) { + const setter = def.flags[flag] && def.flags[flag].setter || flag; + Assert(typeof schema[setter] === 'function', 'Invalid flag', flag, 'for type', desc.type); + schema = schema[setter](this.build(desc.flags[flag])); } - - node = next; } - node[internals.value] = value; - } - - get(path) { + // Preferences - const node = this.node(path); - if (node) { - return node[internals.value]; + if (desc.preferences) { + schema = schema.preferences(this.build(desc.preferences)); } - } - node(path) { + // Allow / Invalid - if (!this._values) { - return; + if (desc.allow) { + schema = schema.allow(...this.build(desc.allow)); } - return Reach(this._values, path, { iterables: true }); - } - - override(path, node) { - - if (!this._values) { - return; + if (desc.invalid) { + schema = schema.invalid(...this.build(desc.invalid)); } - const parents = path.slice(0, -1); - const own = path[path.length - 1]; - const parent = Reach(this._values, parents, { iterables: true }); - - if (node) { - parent.set(own, node); - return; - } + // Rules - if (parent) { - parent.delete(own); - } - } -}; + if (desc.rules) { + for (const rule of desc.rules) { + Assert(typeof schema[rule.name] === 'function', 'Invalid rule', rule.name, 'for type', desc.type); + const args = []; + if (rule.args) { + const built = {}; + for (const key in rule.args) { + built[key] = this.build(rule.args[key], { assign: key }); + } -/***/ }), + const keys = Object.keys(built); + const definition = def.rules[rule.name].args; + if (definition) { + Assert(keys.length <= definition.length, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to', definition.length, ', found', keys.length, ')'); + for (const { name } of definition) { + args.push(built[name]); + } + } + else { + Assert(keys.length === 1, 'Invalid number of arguments for', desc.type, rule.name, '(expected up to 1, found', keys.length, ')'); + args.push(built[keys[0]]); + } + } -/***/ 51396: -/***/ ((module, exports, __nccwpck_require__) => { + // Apply -"use strict"; + schema = schema[rule.name](...args); + // Ruleset -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const EscapeHtml = __nccwpck_require__(24752); -const Formula = __nccwpck_require__(34379); + const options = {}; + for (const custom in def.modifiers) { + if (rule[custom] !== undefined) { + options[custom] = this.build(rule[custom]); + } + } -const Common = __nccwpck_require__(72448); -const Errors = __nccwpck_require__(69490); -const Ref = __nccwpck_require__(73838); + if (Object.keys(options).length) { + schema = schema.rule(options); + } + } + } + // Terms -const internals = { - symbol: Symbol('template'), + const terms = {}; + for (const key in desc) { + if (['allow', 'flags', 'invalid', 'whens', 'preferences', 'rules', 'type'].includes(key)) { + continue; + } - opens: new Array(1000).join('\u0000'), - closes: new Array(1000).join('\u0001'), + Assert(def.terms[key], 'Term', key, 'missing configuration'); + const manifest = def.terms[key].manifest; - dateFormat: { - date: Date.prototype.toDateString, - iso: Date.prototype.toISOString, - string: Date.prototype.toString, - time: Date.prototype.toTimeString, - utc: Date.prototype.toUTCString - } -}; + if (manifest === 'schema') { + terms[key] = desc[key].map((item) => this.parse(item)); + continue; + } + if (manifest === 'values') { + terms[key] = desc[key].map((item) => this.build(item)); + continue; + } -module.exports = exports = internals.Template = class { + if (manifest === 'single') { + terms[key] = this.build(desc[key]); + continue; + } - constructor(source, options) { + if (typeof manifest === 'object') { + terms[key] = {}; + for (const name in desc[key]) { + const value = desc[key][name]; + terms[key][name] = this.parse(value); + } - Assert(typeof source === 'string', 'Template source must be a string'); - Assert(!source.includes('\u0000') && !source.includes('\u0001'), 'Template source cannot contain reserved control characters'); + continue; + } - this.source = source; - this.rendered = source; + terms[key] = this.build(desc[key]); + } - this._template = null; - this._settings = Clone(options); + if (desc.whens) { + terms.whens = desc.whens.map((when) => this.build(when)); + } - this._parse(); + schema = def.manifest.build(schema, terms); + schema.$_temp.ruleset = false; + return schema; } - _parse() { - - // 'text {raw} {{ref}} \\{{ignore}} {{ignore\\}} {{ignore {{ignore}' + build(desc, options = {}) { - if (!this.source.includes('{')) { - return; + if (desc === null) { + return null; } - // Encode escaped \\{{{{{ + if (Array.isArray(desc)) { + return desc.map((item) => this.build(item)); + } - const encoded = internals.encode(this.source); + if (desc instanceof Error) { + return desc; + } - // Split on first { in each set + if (options.assign === 'options') { + return Clone(desc); + } - const parts = internals.split(encoded); + if (options.assign === 'regex') { + return internals.regex(desc); + } - // Process parts + if (options.assign === 'ref') { + return Ref.build(desc); + } - let refs = false; - const processed = []; - const head = parts.shift(); - if (head) { - processed.push(head); + if (typeof desc !== 'object') { + return desc; } - for (const part of parts) { - const raw = part[0] !== '{'; - const ender = raw ? '}' : '}}'; - const end = part.indexOf(ender); - if (end === -1 || // Ignore non-matching closing - part[1] === '{') { // Ignore more than two { + if (Object.keys(desc).length === 1) { + if (desc.buffer) { + Assert(Buffer, 'Buffers are not supported'); + return Buffer && Buffer.from(desc.buffer, 'binary'); // $lab:coverage:ignore$ + } - processed.push(`{${internals.decode(part)}`); - continue; + if (desc.function) { + return { [Common.symbols.literal]: true, literal: desc.function }; } - let variable = part.slice(raw ? 0 : 1, end); - const wrapped = variable[0] === ':'; - if (wrapped) { - variable = variable.slice(1); + if (desc.override) { + return Common.symbols.override; } - const dynamic = this._ref(internals.decode(variable), { raw, wrapped }); - processed.push(dynamic); - if (typeof dynamic !== 'string') { - refs = true; + if (desc.ref) { + return Ref.build(desc.ref); } - const rest = part.slice(end + ender.length); - if (rest) { - processed.push(internals.decode(rest)); + if (desc.regex) { + return internals.regex(desc.regex); + } + + if (desc.special) { + Assert(['deep'].includes(desc.special), 'Unknown special value', desc.special); + return Common.symbols.deepDefault; + } + + if (desc.value) { + return Clone(desc.value); } } - if (!refs) { - this.rendered = processed.join(''); - return; + if (desc.type) { + return this.parse(desc); } - this._template = processed; - } + if (desc.template) { + return Template.build(desc); + } - static date(date, prefs) { + const normalized = {}; + for (const key in desc) { + normalized[key] = this.build(desc[key], { assign: key }); + } - return internals.dateFormat[prefs.dateFormat].call(date); + return normalized; } +}; - describe(options = {}) { - if (!this._settings && - options.compact) { +internals.regex = function (string) { - return this.source; - } + const end = string.lastIndexOf('/'); + const exp = string.slice(1, end); + const flags = string.slice(end + 1); + return new RegExp(exp, flags); +}; - const desc = { template: this.source }; - if (this._settings) { - desc.options = this._settings; - } - return desc; - } +internals.validate = function (joi, desc) { - static build(desc) { + Schemas = Schemas || __nccwpck_require__(85614); - return new internals.Template(desc.template, desc.options); - } + joi.assert(desc, Schemas.description); +}; - isDynamic() { - return !!this._template; +/***/ }), + +/***/ 86103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); + +const Template = __nccwpck_require__(51396); + + +const internals = {}; + + +exports.compile = function (messages, target) { + + // Single value string ('plain error message', 'template {error} message') + + if (typeof messages === 'string') { + Assert(!target, 'Cannot set single message string'); + return new Template(messages); } - static isTemplate(template) { + // Single value template - return template ? !!template[Common.symbols.template] : false; + if (Template.isTemplate(messages)) { + Assert(!target, 'Cannot set single message template'); + return messages; } - refs() { + // By error code { 'number.min': } - if (!this._template) { - return; + Assert(typeof messages === 'object' && !Array.isArray(messages), 'Invalid message options'); + + target = target ? Clone(target) : {}; + + for (let code in messages) { + const message = messages[code]; + + if (code === 'root' || + Template.isTemplate(message)) { + + target[code] = message; + continue; } - const refs = []; - for (const part of this._template) { - if (typeof part !== 'string') { - refs.push(...part.refs); - } + if (typeof message === 'string') { + target[code] = new Template(message); + continue; } - return refs; - } + // By language { english: { 'number.min': } } - resolve(value, state, prefs, local) { + Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); - if (this._template && - this._template.length === 1) { + const language = code; + target[language] = target[language] || {}; - return this._part(this._template[0], /* context -> [*/ value, state, prefs, local, {} /*] */); - } + for (code in message) { + const localized = message[code]; - return this.render(value, state, prefs, local); - } + if (code === 'root' || + Template.isTemplate(localized)) { - _part(part, ...args) { + target[language][code] = localized; + continue; + } - if (part.ref) { - return part.ref.resolve(...args); + Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); + target[language][code] = new Template(localized); } - - return part.formula.evaluate(args); } - render(value, state, prefs, local, options = {}) { + return target; +}; - if (!this.isDynamic()) { - return this.rendered; - } - const parts = []; - for (const part of this._template) { - if (typeof part === 'string') { - parts.push(part); - } - else { - const rendered = this._part(part, /* context -> [*/ value, state, prefs, local, options /*] */); - const string = internals.stringify(rendered, value, state, prefs, local, options); - if (string !== undefined) { - const result = part.raw || (options.errors && options.errors.escapeHtml) === false ? string : EscapeHtml(string); - parts.push(internals.wrap(result, part.wrapped && prefs.errors.wrap.label)); - } - } - } +exports.decompile = function (messages) { - return parts.join(''); - } + // By error code { 'number.min': } - _ref(content, { raw, wrapped }) { + const target = {}; + for (let code in messages) { + const message = messages[code]; - const refs = []; - const reference = (variable) => { + if (code === 'root') { + target.root = message; + continue; + } + + if (Template.isTemplate(message)) { + target[code] = message.describe({ compact: true }); + continue; + } + + // By language { english: { 'number.min': } } - const ref = Ref.create(variable, this._settings); - refs.push(ref); - return (context) => ref.resolve(...context); - }; + const language = code; + target[language] = {}; - try { - var formula = new Formula.Parser(content, { reference, functions: internals.functions, constants: internals.constants }); - } - catch (err) { - err.message = `Invalid template variable "${content}" fails due to: ${err.message}`; - throw err; - } + for (code in message) { + const localized = message[code]; - if (formula.single) { - if (formula.single.type === 'reference') { - const ref = refs[0]; - return { ref, raw, refs, wrapped: wrapped || ref.type === 'local' && ref.key === 'label' }; + if (code === 'root') { + target[language].root = localized; + continue; } - return internals.stringify(formula.single.value); + target[language][code] = localized.describe({ compact: true }); } - - return { formula, raw, refs }; } - toString() { + return target; +}; - return this.source; + +exports.merge = function (base, extended) { + + if (!base) { + return exports.compile(extended); } -}; + if (!extended) { + return base; + } -internals.Template.prototype[Common.symbols.template] = true; -internals.Template.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects + // Single value string + if (typeof extended === 'string') { + return new Template(extended); + } -internals.encode = function (string) { + // Single value template - return string - .replace(/\\(\{+)/g, ($0, $1) => { + if (Template.isTemplate(extended)) { + return extended; + } - return internals.opens.slice(0, $1.length); - }) - .replace(/\\(\}+)/g, ($0, $1) => { + // By error code { 'number.min': } - return internals.closes.slice(0, $1.length); - }); -}; + const target = Clone(base); + for (let code in extended) { + const message = extended[code]; -internals.decode = function (string) { + if (code === 'root' || + Template.isTemplate(message)) { - return string - .replace(/\u0000/g, '{') - .replace(/\u0001/g, '}'); -}; + target[code] = message; + continue; + } + if (typeof message === 'string') { + target[code] = new Template(message); + continue; + } -internals.split = function (string) { + // By language { english: { 'number.min': } } - const parts = []; - let current = ''; + Assert(typeof message === 'object' && !Array.isArray(message), 'Invalid message for', code); - for (let i = 0; i < string.length; ++i) { - const char = string[i]; + const language = code; + target[language] = target[language] || {}; - if (char === '{') { - let next = ''; - while (i + 1 < string.length && - string[i + 1] === '{') { + for (code in message) { + const localized = message[code]; - next += '{'; - ++i; + if (code === 'root' || + Template.isTemplate(localized)) { + + target[language][code] = localized; + continue; } - parts.push(current); - current = next; - } - else { - current += char; + Assert(typeof localized === 'string', 'Invalid message for', code, 'in', language); + target[language][code] = new Template(localized); } } - parts.push(current); - return parts; + return target; }; -internals.wrap = function (value, ends) { +/***/ }), - if (!ends) { - return value; - } +/***/ 81290: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (ends.length === 1) { - return `${ends}${value}${ends}`; - } +"use strict"; - return `${ends[0]}${value}${ends[1]}`; -}; +const Assert = __nccwpck_require__(32718); -internals.stringify = function (value, original, state, prefs, local, options = {}) { +const Common = __nccwpck_require__(72448); +const Ref = __nccwpck_require__(73838); - const type = typeof value; - const wrap = prefs && prefs.errors && prefs.errors.wrap || {}; - let skipWrap = false; - if (Ref.isRef(value) && - value.render) { +const internals = {}; - skipWrap = value.in; - value = value.resolve(original, state, prefs, local, { in: value.in, ...options }); - } - if (value === null) { - return 'null'; - } - if (type === 'string') { - return internals.wrap(value, options.arrayItems && wrap.string); - } +exports.Ids = internals.Ids = class { - if (type === 'number' || - type === 'function' || - type === 'symbol') { + constructor() { - return value.toString(); + this._byId = new Map(); + this._byKey = new Map(); + this._schemaChain = false; } - if (type !== 'object') { - return JSON.stringify(value); - } + clone() { - if (value instanceof Date) { - return internals.Template.date(value, prefs); + const clone = new internals.Ids(); + clone._byId = new Map(this._byId); + clone._byKey = new Map(this._byKey); + clone._schemaChain = this._schemaChain; + return clone; } - if (value instanceof Map) { - const pairs = []; - for (const [key, sym] of value.entries()) { - pairs.push(`${key.toString()} -> ${sym.toString()}`); - } + concat(source) { - value = pairs; - } + if (source._schemaChain) { + this._schemaChain = true; + } - if (!Array.isArray(value)) { - return value.toString(); - } + for (const [id, value] of source._byId.entries()) { + Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); + this._byId.set(id, value); + } - const values = []; - for (const item of value) { - values.push(internals.stringify(item, original, state, prefs, local, { arrayItems: true, ...options })); + for (const [key, value] of source._byKey.entries()) { + Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); + this._byKey.set(key, value); + } } - return internals.wrap(values.join(', '), !skipWrap && wrap.array); -}; - - -internals.constants = { - - true: true, - false: false, - null: null, - - second: 1000, - minute: 60 * 1000, - hour: 60 * 60 * 1000, - day: 24 * 60 * 60 * 1000 -}; + fork(path, adjuster, root) { + const chain = this._collect(path); + chain.push({ schema: root }); + const tail = chain.shift(); + let adjusted = { id: tail.id, schema: adjuster(tail.schema) }; -internals.functions = { + Assert(Common.isSchema(adjusted.schema), 'adjuster function failed to return a joi schema type'); - if(condition, then, otherwise) { + for (const node of chain) { + adjusted = { id: node.id, schema: internals.fork(node.schema, adjusted.id, adjusted.schema) }; + } - return condition ? then : otherwise; - }, + return adjusted.schema; + } - length(item) { + labels(path, behind = []) { - if (typeof item === 'string') { - return item.length; + const current = path[0]; + const node = this._get(current); + if (!node) { + return [...behind, ...path].join('.'); } - if (!item || typeof item !== 'object') { - return null; + const forward = path.slice(1); + behind = [...behind, node.schema._flags.label || current]; + if (!forward.length) { + return behind.join('.'); } - if (Array.isArray(item)) { - return item.length; - } + return node.schema._ids.labels(forward, behind); + } - return Object.keys(item).length; - }, + reach(path, behind = []) { - msg(code) { + const current = path[0]; + const node = this._get(current); + Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); - const [value, state, prefs, local, options] = this; - const messages = options.messages; - if (!messages) { - return ''; + const forward = path.slice(1); + if (!forward.length) { + return node.schema; } - const template = Errors.template(value, messages[0], code, state, prefs) || Errors.template(value, messages[1], code, state, prefs); - if (!template) { - return ''; - } + return node.schema._ids.reach(forward, [...behind, current]); + } - return template.render(value, state, prefs, local, options); - }, + register(schema, { key } = {}) { - number(value) { + if (!schema || + !Common.isSchema(schema)) { - if (typeof value === 'number') { - return value; + return; } - if (typeof value === 'string') { - return parseFloat(value); - } + if (schema.$_property('schemaChain') || + schema._ids._schemaChain) { - if (typeof value === 'boolean') { - return value ? 1 : 0; + this._schemaChain = true; } - if (value instanceof Date) { - return value.getTime(); + const id = schema._flags.id; + if (id) { + const existing = this._byId.get(id); + Assert(!existing || existing.schema === schema, 'Cannot add different schemas with the same id:', id); + Assert(!this._byKey.has(id), 'Schema id conflicts with existing key:', id); + + this._byId.set(id, { schema, id }); } - return null; + if (key) { + Assert(!this._byKey.has(key), 'Schema already contains key:', key); + Assert(!this._byId.has(key), 'Schema key conflicts with existing id:', key); + + this._byKey.set(key, { schema, id: key }); + } } -}; + reset() { -/***/ }), + this._byId = new Map(); + this._byKey = new Map(); + this._schemaChain = false; + } -/***/ 43171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + _collect(path, behind = [], nodes = []) { -"use strict"; + const current = path[0]; + const node = this._get(current); + Assert(node, 'Schema does not contain path', [...behind, ...path].join('.')); + nodes = [node, ...nodes]; -const DeepEqual = __nccwpck_require__(55801); -const Pinpoint = __nccwpck_require__(75604); + const forward = path.slice(1); + if (!forward.length) { + return nodes; + } -const Errors = __nccwpck_require__(69490); + return node.schema._ids._collect(forward, [...behind, current], nodes); + } + _get(id) { -const internals = { - codes: { - error: 1, - pass: 2, - full: 3 - }, - labels: { - 0: 'never used', - 1: 'always error', - 2: 'always pass' + return this._byId.get(id) || this._byKey.get(id); } }; -exports.setup = function (root) { +internals.fork = function (schema, id, replacement) { - const trace = function () { + const each = (item, { key }) => { - root._tracer = root._tracer || new internals.Tracer(); - return root._tracer; + if (id === (item._flags.id || key)) { + return replacement; + } }; - root.trace = trace; - root[Symbol.for('@hapi/lab/coverage/initialize')] = trace; - - root.untrace = () => { - - root._tracer = null; - }; + const obj = exports.schema(schema, { each, ref: false }); + return obj ? obj.$_mutateRebuild() : schema; }; -exports.location = function (schema) { +exports.schema = function (schema, options) { - return schema.$_setFlag('_tracerLocation', Pinpoint.location(2)); // base.tracer(), caller -}; + let obj; + for (const name in schema._flags) { + if (name[0] === '_') { + continue; + } -internals.Tracer = class { + const result = internals.scan(schema._flags[name], { source: 'flags', name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + obj._flags[name] = result; + } + } - constructor() { + for (let i = 0; i < schema._rules.length; ++i) { + const rule = schema._rules[i]; + const result = internals.scan(rule.args, { source: 'rules', name: rule.name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + const clone = Object.assign({}, rule); + clone.args = result; + obj._rules[i] = clone; - this.name = 'Joi'; - this._schemas = new Map(); + const existingUnique = obj._singleRules.get(rule.name); + if (existingUnique === rule) { + obj._singleRules.set(rule.name, clone); + } + } } - _register(schema) { + for (const name in schema.$_terms) { + if (name[0] === '_') { + continue; + } - const existing = this._schemas.get(schema); - if (existing) { - return existing.store; + const result = internals.scan(schema.$_terms[name], { source: 'terms', name }, options); + if (result !== undefined) { + obj = obj || schema.clone(); + obj.$_terms[name] = result; } + } - const store = new internals.Store(schema); - const { filename, line } = schema._flags._tracerLocation || Pinpoint.location(5); // internals.tracer(), internals.entry(), exports.entry(), validate(), caller - this._schemas.set(schema, { filename, line, store }); - return store; + return obj; +}; + + +internals.scan = function (item, source, options, _path, _key) { + + const path = _path || []; + + if (item === null || + typeof item !== 'object') { + + return; } - _combine(merged, sources) { + let clone; - for (const { store } of this._schemas.values()) { - store._combine(merged, sources); + if (Array.isArray(item)) { + for (let i = 0; i < item.length; ++i) { + const key = source.source === 'terms' && source.name === 'keys' && item[i].key; + const result = internals.scan(item[i], source, options, [i, ...path], key); + if (result !== undefined) { + clone = clone || item.slice(); + clone[i] = result; + } } - } - report(file) { + return clone; + } - const coverage = []; + if (options.schema !== false && Common.isSchema(item) || + options.ref !== false && Ref.isRef(item)) { - // Process each registered schema + const result = options.each(item, { ...source, path, key: _key }); + if (result === item) { + return; + } - for (const { filename, line, store } of this._schemas.values()) { - if (file && - file !== filename) { + return result; + } - continue; - } + for (const key in item) { + if (key[0] === '_') { + continue; + } - // Process sub schemas of the registered root + const result = internals.scan(item[key], source, options, [key, ...path], _key); + if (result !== undefined) { + clone = clone || Object.assign({}, item); + clone[key] = result; + } + } - const missing = []; - const skipped = []; + return clone; +}; - for (const [schema, log] of store._sources.entries()) { - // Check if sub schema parent skipped +/***/ }), - if (internals.sub(log.paths, skipped)) { - continue; - } +/***/ 73838: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Check if sub schema reached +"use strict"; - if (!log.entry) { - missing.push({ - status: 'never reached', - paths: [...log.paths] - }); - skipped.push(...log.paths); - continue; - } +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Reach = __nccwpck_require__(18891); - // Check values +const Common = __nccwpck_require__(72448); - for (const type of ['valid', 'invalid']) { - const set = schema[`_${type}s`]; - if (!set) { - continue; - } +let Template; - const values = new Set(set._values); - const refs = new Set(set._refs); - for (const { value, ref } of log[type]) { - values.delete(value); - refs.delete(ref); - } - if (values.size || - refs.size) { +const internals = { + symbol: Symbol('ref'), // Used to internally identify references (shared with other joi versions) + defaults: { + adjust: null, + in: false, + iterables: null, + map: null, + separator: '.', + type: 'value' + } +}; - missing.push({ - status: [...values, ...[...refs].map((ref) => ref.display)], - rule: `${type}s` - }); - } - } - // Check rules status +exports.create = function (key, options = {}) { - const rules = schema._rules.map((rule) => rule.name); - for (const type of ['default', 'failover']) { - if (schema._flags[type] !== undefined) { - rules.push(type); - } - } + Assert(typeof key === 'string', 'Invalid reference key:', key); + Common.assertOptions(options, ['adjust', 'ancestor', 'in', 'iterables', 'map', 'prefix', 'render', 'separator']); + Assert(!options.prefix || typeof options.prefix === 'object', 'options.prefix must be of type object'); - for (const name of rules) { - const status = internals.labels[log.rule[name] || 0]; - if (status) { - const report = { rule: name, status }; - if (log.paths.size) { - report.paths = [...log.paths]; - } + const ref = Object.assign({}, internals.defaults, options); + delete ref.prefix; - missing.push(report); - } - } - } + const separator = ref.separator; + const context = internals.context(key, separator, options.prefix); + ref.type = context.type; + key = context.key; - if (missing.length) { - coverage.push({ - filename, - line, - missing, - severity: 'error', - message: `Schema missing tests for ${missing.map(internals.message).join(', ')}` - }); + if (ref.type === 'value') { + if (context.root) { + Assert(!separator || key[0] !== separator, 'Cannot specify relative path with root prefix'); + ref.ancestor = 'root'; + if (!key) { + key = null; } } - return coverage.length ? coverage : null; - } -}; - - -internals.Store = class { + if (separator && + separator === key) { - constructor(schema) { + key = null; + ref.ancestor = 0; + } + else { + if (ref.ancestor !== undefined) { + Assert(!separator || !key || key[0] !== separator, 'Cannot combine prefix with ancestor option'); + } + else { + const [ancestor, slice] = internals.ancestor(key, separator); + if (slice) { + key = key.slice(slice); + if (key === '') { + key = null; + } + } - this.active = true; - this._sources = new Map(); // schema -> { paths, entry, rule, valid, invalid } - this._combos = new Map(); // merged -> [sources] - this._scan(schema); + ref.ancestor = ancestor; + } + } } - debug(state, source, name, result) { + ref.path = separator ? (key === null ? [] : key.split(separator)) : [key]; - state.mainstay.debug && state.mainstay.debug.push({ type: source, name, result, path: state.path }); - } + return new internals.Ref(ref); +}; - entry(schema, state) { - internals.debug(state, { type: 'entry' }); +exports["in"] = function (key, options = {}) { - this._record(schema, (log) => { + return exports.create(key, { ...options, in: true }); +}; - log.entry = true; - }); - } - filter(schema, state, source, value) { +exports.isRef = function (ref) { - internals.debug(state, { type: source, ...value }); + return ref ? !!ref[Common.symbols.ref] : false; +}; - this._record(schema, (log) => { - log[source].add(value); - }); - } +internals.Ref = class { - log(schema, state, source, name, result) { + constructor(options) { - internals.debug(state, { type: source, name, result: result === 'full' ? 'pass' : result }); + Assert(typeof options === 'object', 'Invalid reference construction'); + Common.assertOptions(options, [ + 'adjust', 'ancestor', 'in', 'iterables', 'map', 'path', 'render', 'separator', 'type', // Copied + 'depth', 'key', 'root', 'display' // Overridden + ]); - this._record(schema, (log) => { + Assert([false, undefined].includes(options.separator) || typeof options.separator === 'string' && options.separator.length === 1, 'Invalid separator'); + Assert(!options.adjust || typeof options.adjust === 'function', 'options.adjust must be a function'); + Assert(!options.map || Array.isArray(options.map), 'options.map must be an array'); + Assert(!options.map || !options.adjust, 'Cannot set both map and adjust options'); - log[source][name] = log[source][name] || 0; - log[source][name] |= internals.codes[result]; - }); - } + Object.assign(this, internals.defaults, options); - resolve(state, ref, to) { + Assert(this.type === 'value' || this.ancestor === undefined, 'Non-value references cannot reference ancestors'); - if (!state.mainstay.debug) { - return; + if (Array.isArray(this.map)) { + this.map = new Map(this.map); } - const log = { type: 'resolve', ref: ref.display, to, path: state.path }; - state.mainstay.debug.push(log); + this.depth = this.path.length; + this.key = this.path.length ? this.path.join(this.separator) : null; + this.root = this.path[0]; + + this.updateDisplay(); } - value(state, by, from, to, name) { + resolve(value, state, prefs, local, options = {}) { - if (!state.mainstay.debug || - DeepEqual(from, to)) { + Assert(!this.in || options.in, 'Invalid in() reference usage'); - return; + if (this.type === 'global') { + return this._resolve(prefs.context, state, options); } - const log = { type: 'value', by, from, to, path: state.path }; - if (name) { - log.name = name; + if (this.type === 'local') { + return this._resolve(local, state, options); } - state.mainstay.debug.push(log); - } - - _record(schema, each) { - - const log = this._sources.get(schema); - if (log) { - each(log); - return; + if (!this.ancestor) { + return this._resolve(value, state, options); } - const sources = this._combos.get(schema); - for (const source of sources) { - this._record(source, each); + if (this.ancestor === 'root') { + return this._resolve(state.ancestors[state.ancestors.length - 1], state, options); } + + Assert(this.ancestor <= state.ancestors.length, 'Invalid reference exceeds the schema root:', this.display); + return this._resolve(state.ancestors[this.ancestor - 1], state, options); } - _scan(schema, _path) { + _resolve(target, state, options) { - const path = _path || []; + let resolved; - let log = this._sources.get(schema); - if (!log) { - log = { - paths: new Set(), - entry: false, - rule: {}, - valid: new Set(), - invalid: new Set() - }; + if (this.type === 'value' && + state.mainstay.shadow && + options.shadow !== false) { - this._sources.set(schema, log); + resolved = state.mainstay.shadow.get(this.absolute(state)); } - if (path.length) { - log.paths.add(path); + if (resolved === undefined) { + resolved = Reach(target, this.path, { iterables: this.iterables, functions: true }); } - const each = (sub, source) => { + if (this.adjust) { + resolved = this.adjust(resolved); + } - const subId = internals.id(sub, source); - this._scan(sub, path.concat(subId)); - }; + if (this.map) { + const mapped = this.map.get(resolved); + if (mapped !== undefined) { + resolved = mapped; + } + } - schema.$_modify({ each, ref: false }); + if (state.mainstay) { + state.mainstay.tracer.resolve(state, this, resolved); + } + + return resolved; } - _combine(merged, sources) { + toString() { - this._combos.set(merged, sources); + return this.display; } -}; + absolute(state) { -internals.message = function (item) { + return [...state.path.slice(0, -this.ancestor), ...this.path]; + } - const path = item.paths ? Errors.path(item.paths[0]) + (item.rule ? ':' : '') : ''; - return `${path}${item.rule || ''} (${item.status})`; -}; + clone() { + return new internals.Ref(this); + } -internals.id = function (schema, { source, name, path, key }) { + describe() { - if (schema._flags.id) { - return schema._flags.id; - } + const ref = { path: this.path }; - if (key) { - return key; - } + if (this.type !== 'value') { + ref.type = this.type; + } - name = `@${name}`; + if (this.separator !== '.') { + ref.separator = this.separator; + } - if (source === 'terms') { - return [name, path[Math.min(path.length - 1, 1)]]; - } + if (this.type === 'value' && + this.ancestor !== 1) { - return name; -}; + ref.ancestor = this.ancestor; + } + if (this.map) { + ref.map = [...this.map]; + } -internals.sub = function (paths, skipped) { + for (const key of ['adjust', 'iterables', 'render']) { + if (this[key] !== null && + this[key] !== undefined) { - for (const path of paths) { - for (const skip of skipped) { - if (DeepEqual(path.slice(0, skip.length), skip)) { - return true; + ref[key] = this[key]; } } - } - return false; -}; + if (this.in !== false) { + ref.in = true; + } + return { ref }; + } -internals.debug = function (state, event) { + updateDisplay() { - if (state.mainstay.debug) { - event.path = state.debug ? [...state.path, state.debug] : state.path; - state.mainstay.debug.push(event); - } -}; + const key = this.key !== null ? this.key : ''; + if (this.type !== 'value') { + this.display = `ref:${this.type}:${key}`; + return; + } + if (!this.separator) { + this.display = `ref:${key}`; + return; + } -/***/ }), + if (!this.ancestor) { + this.display = `ref:${this.separator}${key}`; + return; + } -/***/ 26867: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.ancestor === 'root') { + this.display = `ref:root:${key}`; + return; + } -"use strict"; + if (this.ancestor === 1) { + this.display = `ref:${key || '..'}`; + return; + } + const lead = new Array(this.ancestor + 1).fill(this.separator).join(''); + this.display = `ref:${lead}${key || ''}`; + } +}; -const Assert = __nccwpck_require__(32718); -const Merge = __nccwpck_require__(60445); -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Ref = __nccwpck_require__(73838); +internals.Ref.prototype[Common.symbols.ref] = true; -const internals = {}; +exports.build = function (desc) { + desc = Object.assign({}, internals.defaults, desc); + if (desc.type === 'value' && + desc.ancestor === undefined) { -module.exports = Any.extend({ + desc.ancestor = 1; + } - type: 'alternatives', + return new internals.Ref(desc); +}; - flags: { - match: { default: 'any' } // 'any', 'one', 'all' - }, +internals.context = function (key, separator, prefix = {}) { - terms: { + key = key.trim(); - matches: { init: [], register: Ref.toSibling } - }, + if (prefix) { + const globalp = prefix.global === undefined ? '$' : prefix.global; + if (globalp !== separator && + key.startsWith(globalp)) { - args(schema, ...schemas) { + return { key: key.slice(globalp.length), type: 'global' }; + } - if (schemas.length === 1) { - if (Array.isArray(schemas[0])) { - return schema.try(...schemas[0]); - } + const local = prefix.local === undefined ? '#' : prefix.local; + if (local !== separator && + key.startsWith(local)) { + + return { key: key.slice(local.length), type: 'local' }; } - return schema.try(...schemas); - }, + const root = prefix.root === undefined ? '/' : prefix.root; + if (root !== separator && + key.startsWith(root)) { - validate(value, helpers) { + return { key: key.slice(root.length), type: 'value', root: true }; + } + } - const { schema, error, state, prefs } = helpers; + return { key, type: 'value' }; +}; - // Match all or one - if (schema._flags.match) { - const matched = []; - const failed = []; +internals.ancestor = function (key, separator) { - for (let i = 0; i < schema.$_terms.matches.length; ++i) { - const item = schema.$_terms.matches[i]; - const localState = state.nest(item.schema, `match.${i}`); - localState.snapshot(); + if (!separator) { + return [1, 0]; // 'a_b' -> 1 (parent) + } - const result = item.schema.$_validate(value, localState, prefs); - if (!result.errors) { - matched.push(result.value); - localState.commit(); - } - else { - failed.push(result.errors); - localState.restore(); - } - } + if (key[0] !== separator) { // 'a.b' -> 1 (parent) + return [1, 0]; + } - if (matched.length === 0) { - const context = { - details: failed.map((f) => Errors.details(f, { override: false })) - }; + if (key[1] !== separator) { // '.a.b' -> 0 (self) + return [0, 1]; + } - return { errors: error('alternatives.any', context) }; - } + let i = 2; + while (key[i] === separator) { + ++i; + } - // Match one + return [i - 1, i]; // '...a.b.' -> 2 (grandparent) +}; - if (schema._flags.match === 'one') { - return matched.length === 1 ? { value: matched[0] } : { errors: error('alternatives.one') }; - } - // Match all +exports.toSibling = 0; - if (matched.length !== schema.$_terms.matches.length) { - const context = { - details: failed.map((f) => Errors.details(f, { override: false })) - }; +exports.toParent = 1; - return { errors: error('alternatives.all', context) }; - } - const isAnyObj = (alternative) => { +exports.Manager = class { - return alternative.$_terms.matches.some((v) => { + constructor() { - return v.schema.type === 'object' || - (v.schema.type === 'alternatives' && isAnyObj(v.schema)); - }); - }; + this.refs = []; // 0: [self refs], 1: [parent refs], 2: [grandparent refs], ... + } - return isAnyObj(schema) ? { value: matched.reduce((acc, v) => Merge(acc, v, { mergeArrays: false })) } : { value: matched[matched.length - 1] }; + register(source, target) { + + if (!source) { + return; } - // Match any + target = target === undefined ? exports.toParent : target; - const errors = []; - for (let i = 0; i < schema.$_terms.matches.length; ++i) { - const item = schema.$_terms.matches[i]; + // Array - // Try + if (Array.isArray(source)) { + for (const ref of source) { + this.register(ref, target); + } - if (item.schema) { - const localState = state.nest(item.schema, `match.${i}`); - localState.snapshot(); + return; + } - const result = item.schema.$_validate(value, localState, prefs); - if (!result.errors) { - localState.commit(); - return result; - } + // Schema - localState.restore(); - errors.push({ schema: item.schema, reports: result.errors }); - continue; + if (Common.isSchema(source)) { + for (const item of source._refs.refs) { + if (item.ancestor - target >= 0) { + this.refs.push({ ancestor: item.ancestor - target, root: item.root }); + } } - // Conditional + return; + } - const input = item.ref ? item.ref.resolve(value, state, prefs) : value; - const tests = item.is ? [item] : item.switch; + // Reference - for (let j = 0; j < tests.length; ++j) { - const test = tests[j]; - const { is, then, otherwise } = test; + if (exports.isRef(source) && + source.type === 'value' && + source.ancestor - target >= 0) { - const id = `match.${i}${item.switch ? '.' + j : ''}`; - if (!is.$_match(input, state.nest(is, `${id}.is`), prefs)) { - if (otherwise) { - return otherwise.$_validate(value, state.nest(otherwise, `${id}.otherwise`), prefs); - } - } - else if (then) { - return then.$_validate(value, state.nest(then, `${id}.then`), prefs); - } - } + this.refs.push({ ancestor: source.ancestor - target, root: source.root }); } - return internals.errors(errors, helpers); - }, + // Template - rules: { + Template = Template || __nccwpck_require__(51396); - conditional: { - method(condition, options) { + if (Template.isTemplate(source)) { + this.register(source.refs(), target); + } + } - Assert(!this._flags._endedSwitch, 'Unreachable condition'); - Assert(!this._flags.match, 'Cannot combine match mode', this._flags.match, 'with conditional rule'); - Assert(options.break === undefined, 'Cannot use break option with alternatives conditional'); + get length() { - const obj = this.clone(); + return this.refs.length; + } - const match = Compile.when(obj, condition, options); - const conditions = match.is ? [match] : match.switch; - for (const item of conditions) { - if (item.then && - item.otherwise) { + clone() { - obj.$_setFlag('_endedSwitch', true, { clone: false }); - break; - } - } + const copy = new exports.Manager(); + copy.refs = Clone(this.refs); + return copy; + } - obj.$_terms.matches.push(match); - return obj.$_mutateRebuild(); - } - }, + reset() { - match: { - method(mode) { + this.refs = []; + } + + roots() { + + return this.refs.filter((ref) => !ref.ancestor).map((ref) => ref.root); + } +}; + + +/***/ }), - Assert(['any', 'one', 'all'].includes(mode), 'Invalid alternatives match mode', mode); +/***/ 85614: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (mode !== 'any') { - for (const match of this.$_terms.matches) { - Assert(match.schema, 'Cannot combine match mode', mode, 'with conditional rules'); - } - } +"use strict"; - return this.$_setFlag('match', mode); - } - }, - try: { - method(...schemas) { +const Joi = __nccwpck_require__(20918); - Assert(schemas.length, 'Missing alternative schemas'); - Common.verifyFlat(schemas, 'try'); - Assert(!this._flags._endedSwitch, 'Unreachable condition'); +const internals = {}; - const obj = this.clone(); - for (const schema of schemas) { - obj.$_terms.matches.push({ schema: obj.$_compile(schema) }); - } - return obj.$_mutateRebuild(); - } - } - }, +// Preferences - overrides: { +internals.wrap = Joi.string() + .min(1) + .max(2) + .allow(false); - label(name) { - const obj = this.$_parent('label', name); - const each = (item, source) => (source.path[0] !== 'is' ? item.label(name) : undefined); - return obj.$_modify({ each, ref: false }); +exports.preferences = Joi.object({ + allowUnknown: Joi.boolean(), + abortEarly: Joi.boolean(), + artifacts: Joi.boolean(), + cache: Joi.boolean(), + context: Joi.object(), + convert: Joi.boolean(), + dateFormat: Joi.valid('date', 'iso', 'string', 'time', 'utc'), + debug: Joi.boolean(), + errors: { + escapeHtml: Joi.boolean(), + label: Joi.valid('path', 'key', false), + language: [ + Joi.string(), + Joi.object().ref() + ], + render: Joi.boolean(), + stack: Joi.boolean(), + wrap: { + label: internals.wrap, + array: internals.wrap, + string: internals.wrap } }, + externals: Joi.boolean(), + messages: Joi.object(), + noDefaults: Joi.boolean(), + nonEnumerables: Joi.boolean(), + presence: Joi.valid('required', 'optional', 'forbidden'), + skipFunctions: Joi.boolean(), + stripUnknown: Joi.object({ + arrays: Joi.boolean(), + objects: Joi.boolean() + }) + .or('arrays', 'objects') + .allow(true, false), + warnings: Joi.boolean() +}) + .strict(); - rebuild(schema) { - // Flag when an alternative type is an array +// Extensions - const each = (item) => { +internals.nameRx = /^[a-zA-Z0-9]\w*$/; - if (Common.isSchema(item) && - item.type === 'array') { - schema.$_setFlag('_arrayItems', true, { clone: false }); - } - }; +internals.rule = Joi.object({ + alias: Joi.array().items(Joi.string().pattern(internals.nameRx)).single(), + args: Joi.array().items( + Joi.string(), + Joi.object({ + name: Joi.string().pattern(internals.nameRx).required(), + ref: Joi.boolean(), + assert: Joi.alternatives([ + Joi.function(), + Joi.object().schema() + ]) + .conditional('ref', { is: true, then: Joi.required() }), + normalize: Joi.function(), + message: Joi.string().when('assert', { is: Joi.function(), then: Joi.required() }) + }) + ), + convert: Joi.boolean(), + manifest: Joi.boolean(), + method: Joi.function().allow(false), + multi: Joi.boolean(), + validate: Joi.function() +}); - schema.$_modify({ each }); - }, +exports.extension = Joi.object({ + type: Joi.alternatives([ + Joi.string(), + Joi.object().regex() + ]) + .required(), + args: Joi.function(), + cast: Joi.object().pattern(internals.nameRx, Joi.object({ + from: Joi.function().maxArity(1).required(), + to: Joi.function().minArity(1).maxArity(2).required() + })), + base: Joi.object().schema() + .when('type', { is: Joi.object().regex(), then: Joi.forbidden() }), + coerce: [ + Joi.function().maxArity(3), + Joi.object({ method: Joi.function().maxArity(3).required(), from: Joi.array().items(Joi.string()).single() }) + ], + flags: Joi.object().pattern(internals.nameRx, Joi.object({ + setter: Joi.string(), + default: Joi.any() + })), manifest: { + build: Joi.function().arity(2) + }, + messages: [Joi.object(), Joi.string()], + modifiers: Joi.object().pattern(internals.nameRx, Joi.function().minArity(1).maxArity(2)), + overrides: Joi.object().pattern(internals.nameRx, Joi.function()), + prepare: Joi.function().maxArity(3), + rebuild: Joi.function().arity(1), + rules: Joi.object().pattern(internals.nameRx, internals.rule), + terms: Joi.object().pattern(internals.nameRx, Joi.object({ + init: Joi.array().allow(null).required(), + manifest: Joi.object().pattern(/.+/, [ + Joi.valid('schema', 'single'), + Joi.object({ + mapped: Joi.object({ + from: Joi.string().required(), + to: Joi.string().required() + }) + .required() + }) + ]) + })), + validate: Joi.function().maxArity(3) +}) + .strict(); - build(obj, desc) { - if (desc.matches) { - for (const match of desc.matches) { - const { schema, ref, is, not, then, otherwise } = match; - if (schema) { - obj = obj.try(schema); - } - else if (ref) { - obj = obj.conditional(ref, { is, then, not, otherwise, switch: match.switch }); - } - else { - obj = obj.conditional(is, { then, otherwise }); - } - } - } +exports.extensions = Joi.array().items(Joi.object(), Joi.function().arity(1)).strict(); - return obj; + +// Manifest + +internals.desc = { + + buffer: Joi.object({ + buffer: Joi.string() + }), + + func: Joi.object({ + function: Joi.function().required(), + options: { + literal: true } - }, + }), - messages: { - 'alternatives.all': '{{#label}} does not match all of the required types', - 'alternatives.any': '{{#label}} does not match any of the allowed types', - 'alternatives.match': '{{#label}} does not match any of the allowed types', - 'alternatives.one': '{{#label}} matches more than one allowed type', - 'alternatives.types': '{{#label}} must be one of {{#types}}' - } -}); + override: Joi.object({ + override: true + }), + ref: Joi.object({ + ref: Joi.object({ + type: Joi.valid('value', 'global', 'local'), + path: Joi.array().required(), + separator: Joi.string().length(1).allow(false), + ancestor: Joi.number().min(0).integer().allow('root'), + map: Joi.array().items(Joi.array().length(2)).min(1), + adjust: Joi.function(), + iterables: Joi.boolean(), + in: Joi.boolean(), + render: Joi.boolean() + }) + .required() + }), -// Helpers + regex: Joi.object({ + regex: Joi.string().min(3) + }), -internals.errors = function (failures, { error, state }) { + special: Joi.object({ + special: Joi.valid('deep').required() + }), - // Nothing matched due to type criteria rules + template: Joi.object({ + template: Joi.string().required(), + options: Joi.object() + }), - if (!failures.length) { - return { errors: error('alternatives.any') }; - } + value: Joi.object({ + value: Joi.alternatives([Joi.object(), Joi.array()]).required() + }) +}; - // Single error - if (failures.length === 1) { - return { errors: failures[0].reports }; - } +internals.desc.entity = Joi.alternatives([ + Joi.array().items(Joi.link('...')), + Joi.boolean(), + Joi.function(), + Joi.number(), + Joi.string(), + internals.desc.buffer, + internals.desc.func, + internals.desc.ref, + internals.desc.regex, + internals.desc.special, + internals.desc.template, + internals.desc.value, + Joi.link('/') +]); - // Analyze reasons - const valids = new Set(); - const complex = []; +internals.desc.values = Joi.array() + .items( + null, + Joi.boolean(), + Joi.function(), + Joi.number().allow(Infinity, -Infinity), + Joi.string().allow(''), + Joi.symbol(), + internals.desc.buffer, + internals.desc.func, + internals.desc.override, + internals.desc.ref, + internals.desc.regex, + internals.desc.template, + internals.desc.value + ); - for (const { reports, schema } of failures) { - // Multiple errors (!abortEarly) +internals.desc.messages = Joi.object() + .pattern(/.+/, [ + Joi.string(), + internals.desc.template, + Joi.object().pattern(/.+/, [Joi.string(), internals.desc.template]) + ]); - if (reports.length > 1) { - return internals.unmatched(failures, error); - } - // Custom error +exports.description = Joi.object({ + type: Joi.string().required(), + flags: Joi.object({ + cast: Joi.string(), + default: Joi.any(), + description: Joi.string(), + empty: Joi.link('/'), + failover: internals.desc.entity, + id: Joi.string(), + label: Joi.string(), + only: true, + presence: ['optional', 'required', 'forbidden'], + result: ['raw', 'strip'], + strip: Joi.boolean(), + unit: Joi.string() + }) + .unknown(), + preferences: { + allowUnknown: Joi.boolean(), + abortEarly: Joi.boolean(), + artifacts: Joi.boolean(), + cache: Joi.boolean(), + convert: Joi.boolean(), + dateFormat: ['date', 'iso', 'string', 'time', 'utc'], + errors: { + escapeHtml: Joi.boolean(), + label: ['path', 'key'], + language: [ + Joi.string(), + internals.desc.ref + ], + wrap: { + label: internals.wrap, + array: internals.wrap + } + }, + externals: Joi.boolean(), + messages: internals.desc.messages, + noDefaults: Joi.boolean(), + nonEnumerables: Joi.boolean(), + presence: ['required', 'optional', 'forbidden'], + skipFunctions: Joi.boolean(), + stripUnknown: Joi.object({ + arrays: Joi.boolean(), + objects: Joi.boolean() + }) + .or('arrays', 'objects') + .allow(true, false), + warnings: Joi.boolean() + }, + allow: internals.desc.values, + invalid: internals.desc.values, + rules: Joi.array().min(1).items({ + name: Joi.string().required(), + args: Joi.object().min(1), + keep: Joi.boolean(), + message: [ + Joi.string(), + internals.desc.messages + ], + warn: Joi.boolean() + }), - const report = reports[0]; - if (report instanceof Errors.Report === false) { - return internals.unmatched(failures, error); - } + // Terms - // Internal object or array error + keys: Joi.object().pattern(/.*/, Joi.link('/')), + link: internals.desc.ref +}) + .pattern(/^[a-z]\w*$/, Joi.any()); - if (report.state.path.length !== state.path.length) { - complex.push({ type: schema.type, report }); - continue; - } - // Valids +/***/ }), - if (report.code === 'any.only') { - for (const valid of report.local.valids) { - valids.add(valid); - } +/***/ 73634: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - continue; - } +"use strict"; - // Base type - const [type, code] = report.code.split('.'); - if (code !== 'base') { - complex.push({ type: schema.type, report }); - continue; - } +const Clone = __nccwpck_require__(85578); +const Reach = __nccwpck_require__(18891); - valids.add(type); - } +const Common = __nccwpck_require__(72448); - // All errors are base types or valids - if (!complex.length) { - return { errors: error('alternatives.types', { types: [...valids] }) }; - } +const internals = { + value: Symbol('value') +}; - // Single complex error - if (complex.length === 1) { - return { errors: complex[0].report }; +module.exports = internals.State = class { + + constructor(path, ancestors, state) { + + this.path = path; + this.ancestors = ancestors; // [parent, ..., root] + + this.mainstay = state.mainstay; + this.schemas = state.schemas; // [current, ..., root] + this.debug = null; } - return internals.unmatched(failures, error); -}; + localize(path, ancestors = null, schema = null) { + const state = new internals.State(path, ancestors, this); -internals.unmatched = function (failures, error) { + if (schema && + state.schemas) { - const errors = []; - for (const failure of failures) { - errors.push(...failure.reports); + state.schemas = [internals.schemas(schema), ...state.schemas]; + } + + return state; } - return { errors: error('alternatives.match', Errors.details(errors, { override: false })) }; -}; + nest(schema, debug) { + const state = new internals.State(this.path, this.ancestors, this); + state.schemas = state.schemas && [internals.schemas(schema), ...state.schemas]; + state.debug = debug; + return state; + } -/***/ }), + shadow(value, reason) { -/***/ 9512: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.mainstay.shadow = this.mainstay.shadow || new internals.Shadow(); + this.mainstay.shadow.set(this.path, value, reason); + } -"use strict"; + snapshot() { + if (this.mainstay.shadow) { + this._snapshot = Clone(this.mainstay.shadow.node(this.path)); + } -const Assert = __nccwpck_require__(32718); + this.mainstay.snapshot(); + } -const Base = __nccwpck_require__(95184); -const Common = __nccwpck_require__(72448); -const Messages = __nccwpck_require__(86103); + restore() { + if (this.mainstay.shadow) { + this.mainstay.shadow.override(this.path, this._snapshot); + this._snapshot = undefined; + } -const internals = {}; + this.mainstay.restore(); + } + commit() { -module.exports = Base.extend({ + if (this.mainstay.shadow) { + this.mainstay.shadow.override(this.path, this._snapshot); + this._snapshot = undefined; + } - type: 'any', + this.mainstay.commit(); + } +}; - flags: { - only: { default: false } - }, +internals.schemas = function (schema) { - terms: { + if (Common.isSchema(schema)) { + return { schema }; + } - alterations: { init: null }, - examples: { init: null }, - externals: { init: null }, - metas: { init: [] }, - notes: { init: [] }, - shared: { init: null }, - tags: { init: [] }, - whens: { init: null } - }, + return schema; +}; - rules: { - custom: { - method(method, description) { +internals.Shadow = class { - Assert(typeof method === 'function', 'Method must be a function'); - Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); + constructor() { - return this.$_addRule({ name: 'custom', args: { method, description } }); - }, - validate(value, helpers, { method }) { + this._values = null; + } - try { - return method(value, helpers); - } - catch (err) { - return helpers.error('any.custom', { error: err }); - } - }, - args: ['method', 'description'], - multi: true - }, + set(path, value, reason) { - messages: { - method(messages) { + if (!path.length) { // No need to store root value + return; + } - return this.prefs({ messages }); - } - }, + if (reason === 'strip' && + typeof path[path.length - 1] === 'number') { // Cannot store stripped array values (due to shift) - shared: { - method(schema) { + return; + } - Assert(Common.isSchema(schema) && schema._flags.id, 'Schema must be a schema with an id'); + this._values = this._values || new Map(); - const obj = this.clone(); - obj.$_terms.shared = obj.$_terms.shared || []; - obj.$_terms.shared.push(schema); - obj.$_mutateRegister(schema); - return obj; + let node = this._values; + for (let i = 0; i < path.length; ++i) { + const segment = path[i]; + let next = node.get(segment); + if (!next) { + next = new Map(); + node.set(segment, next); } - }, - warning: { - method(code, local) { + node = next; + } - Assert(code && typeof code === 'string', 'Invalid warning code'); + node[internals.value] = value; + } - return this.$_addRule({ name: 'warning', args: { code, local }, warn: true }); - }, - validate(value, helpers, { code, local }) { + get(path) { - return helpers.error(code, local); - }, - args: ['code', 'local'], - multi: true + const node = this.node(path); + if (node) { + return node[internals.value]; } - }, + } - modifiers: { + node(path) { - keep(rule, enabled = true) { + if (!this._values) { + return; + } - rule.keep = enabled; - }, + return Reach(this._values, path, { iterables: true }); + } - message(rule, message) { + override(path, node) { - rule.message = Messages.compile(message); - }, + if (!this._values) { + return; + } - warn(rule, enabled = true) { + const parents = path.slice(0, -1); + const own = path[path.length - 1]; + const parent = Reach(this._values, parents, { iterables: true }); - rule.warn = enabled; + if (node) { + parent.set(own, node); + return; } - }, - manifest: { + if (parent) { + parent.delete(own); + } + } +}; - build(obj, desc) { - for (const key in desc) { - const values = desc[key]; +/***/ }), - if (['examples', 'externals', 'metas', 'notes', 'tags'].includes(key)) { - for (const value of values) { - obj = obj[key.slice(0, -1)](value); - } +/***/ 51396: +/***/ ((module, exports, __nccwpck_require__) => { - continue; - } +"use strict"; - if (key === 'alterations') { - const alter = {}; - for (const { target, adjuster } of values) { - alter[target] = adjuster; - } - obj = obj.alter(alter); - continue; - } +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const EscapeHtml = __nccwpck_require__(24752); +const Formula = __nccwpck_require__(34379); - if (key === 'whens') { - for (const value of values) { - const { ref, is, not, then, otherwise, concat } = value; - if (concat) { - obj = obj.concat(concat); - } - else if (ref) { - obj = obj.when(ref, { is, not, then, otherwise, switch: value.switch, break: value.break }); - } - else { - obj = obj.when(is, { then, otherwise, break: value.break }); - } - } +const Common = __nccwpck_require__(72448); +const Errors = __nccwpck_require__(69490); +const Ref = __nccwpck_require__(73838); - continue; - } - if (key === 'shared') { - for (const value of values) { - obj = obj.shared(value); - } - } - } +const internals = { + symbol: Symbol('template'), - return obj; - } - }, + opens: new Array(1000).join('\u0000'), + closes: new Array(1000).join('\u0001'), - messages: { - 'any.custom': '{{#label}} failed custom validation because {{#error.message}}', - 'any.default': '{{#label}} threw an error when running default method', - 'any.failover': '{{#label}} threw an error when running failover method', - 'any.invalid': '{{#label}} contains an invalid value', - 'any.only': '{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}', - 'any.ref': '{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}', - 'any.required': '{{#label}} is required', - 'any.unknown': '{{#label}} is not allowed' + dateFormat: { + date: Date.prototype.toDateString, + iso: Date.prototype.toISOString, + string: Date.prototype.toString, + time: Date.prototype.toTimeString, + utc: Date.prototype.toUTCString } -}); +}; -/***/ }), +module.exports = exports = internals.Template = class { -/***/ 20270: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + constructor(source, options) { -"use strict"; + Assert(typeof source === 'string', 'Template source must be a string'); + Assert(!source.includes('\u0000') && !source.includes('\u0001'), 'Template source cannot contain reserved control characters'); + this.source = source; + this.rendered = source; -const Assert = __nccwpck_require__(32718); -const DeepEqual = __nccwpck_require__(55801); -const Reach = __nccwpck_require__(18891); + this._template = null; -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); + if (options) { + const { functions, ...opts } = options; + this._settings = Object.keys(opts).length ? Clone(opts) : undefined; + this._functions = functions; + if (this._functions) { + Assert(Object.keys(this._functions).every((key) => typeof key === 'string'), 'Functions keys must be strings'); + Assert(Object.values(this._functions).every((key) => typeof key === 'function'), 'Functions values must be functions'); + } + } + else { + this._settings = undefined; + this._functions = undefined; + } + this._parse(); + } -const internals = {}; + _parse() { + // 'text {raw} {{ref}} \\{{ignore}} {{ignore\\}} {{ignore {{ignore}' -module.exports = Any.extend({ + if (!this.source.includes('{')) { + return; + } - type: 'array', + // Encode escaped \\{{{{{ - flags: { + const encoded = internals.encode(this.source); - single: { default: false }, - sparse: { default: false } - }, + // Split on first { in each set - terms: { + const parts = internals.split(encoded); - items: { init: [], manifest: 'schema' }, - ordered: { init: [], manifest: 'schema' }, + // Process parts - _exclusions: { init: [] }, - _inclusions: { init: [] }, - _requireds: { init: [] } - }, + let refs = false; + const processed = []; + const head = parts.shift(); + if (head) { + processed.push(head); + } - coerce: { - from: 'object', - method(value, { schema, state, prefs }) { + for (const part of parts) { + const raw = part[0] !== '{'; + const ender = raw ? '}' : '}}'; + const end = part.indexOf(ender); + if (end === -1 || // Ignore non-matching closing + part[1] === '{') { // Ignore more than two { - if (!Array.isArray(value)) { - return; + processed.push(`{${internals.decode(part)}`); + continue; } - const sort = schema.$_getRule('sort'); - if (!sort) { - return; + let variable = part.slice(raw ? 0 : 1, end); + const wrapped = variable[0] === ':'; + if (wrapped) { + variable = variable.slice(1); } - return internals.sort(schema, value, sort.args.options, state, prefs); + const dynamic = this._ref(internals.decode(variable), { raw, wrapped }); + processed.push(dynamic); + if (typeof dynamic !== 'string') { + refs = true; + } + + const rest = part.slice(end + ender.length); + if (rest) { + processed.push(internals.decode(rest)); + } } - }, - validate(value, { schema, error }) { + if (!refs) { + this.rendered = processed.join(''); + return; + } - if (!Array.isArray(value)) { - if (schema._flags.single) { - const single = [value]; - single[Common.symbols.arraySingle] = true; - return { value: single }; - } + this._template = processed; + } - return { errors: error('array.base') }; + static date(date, prefs) { + + return internals.dateFormat[prefs.dateFormat].call(date); + } + + describe(options = {}) { + + if (!this._settings && + options.compact) { + + return this.source; } - if (!schema.$_getRule('items') && - !schema.$_terms.externals) { + const desc = { template: this.source }; + if (this._settings) { + desc.options = this._settings; + } - return; + if (this._functions) { + desc.functions = this._functions; } - return { value: value.slice() }; // Clone the array so that we don't modify the original - }, + return desc; + } - rules: { + static build(desc) { - has: { - method(schema) { + return new internals.Template(desc.template, desc.options || desc.functions ? { ...desc.options, functions: desc.functions } : undefined); + } - schema = this.$_compile(schema, { appendPath: true }); - const obj = this.$_addRule({ name: 'has', args: { schema } }); - obj.$_mutateRegister(schema); - return obj; - }, - validate(value, { state, prefs, error }, { schema: has }) { + isDynamic() { - const ancestors = [value, ...state.ancestors]; - for (let i = 0; i < value.length; ++i) { - const localState = state.localize([...state.path, i], ancestors, has); - if (has.$_match(value[i], localState, prefs)) { - return value; - } - } + return !!this._template; + } - const patternLabel = has._flags.label; - if (patternLabel) { - return error('array.hasKnown', { patternLabel }); - } + static isTemplate(template) { - return error('array.hasUnknown', null); - }, - multi: true - }, + return template ? !!template[Common.symbols.template] : false; + } - items: { - method(...schemas) { + refs() { - Common.verifyFlat(schemas, 'items'); + if (!this._template) { + return; + } - const obj = this.$_addRule('items'); + const refs = []; + for (const part of this._template) { + if (typeof part !== 'string') { + refs.push(...part.refs); + } + } - for (let i = 0; i < schemas.length; ++i) { - const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); - obj.$_terms.items.push(type); - } + return refs; + } - return obj.$_mutateRebuild(); - }, - validate(value, { schema, error, state, prefs, errorsArray }) { + resolve(value, state, prefs, local) { - const requireds = schema.$_terms._requireds.slice(); - const ordereds = schema.$_terms.ordered.slice(); - const inclusions = [...schema.$_terms._inclusions, ...requireds]; + if (this._template && + this._template.length === 1) { - const wasArray = !value[Common.symbols.arraySingle]; - delete value[Common.symbols.arraySingle]; + return this._part(this._template[0], /* context -> [*/ value, state, prefs, local, {} /*] */); + } - const errors = errorsArray(); + return this.render(value, state, prefs, local); + } - let il = value.length; - for (let i = 0; i < il; ++i) { - const item = value[i]; + _part(part, ...args) { - let errored = false; - let isValid = false; + if (part.ref) { + return part.ref.resolve(...args); + } - const key = wasArray ? i : new Number(i); // eslint-disable-line no-new-wrappers - const path = [...state.path, key]; + return part.formula.evaluate(args); + } - // Sparse + render(value, state, prefs, local, options = {}) { - if (!schema._flags.sparse && - item === undefined) { + if (!this.isDynamic()) { + return this.rendered; + } - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } + const parts = []; + for (const part of this._template) { + if (typeof part === 'string') { + parts.push(part); + } + else { + const rendered = this._part(part, /* context -> [*/ value, state, prefs, local, options /*] */); + const string = internals.stringify(rendered, value, state, prefs, local, options); + if (string !== undefined) { + const result = part.raw || (options.errors && options.errors.escapeHtml) === false ? string : EscapeHtml(string); + parts.push(internals.wrap(result, part.wrapped && prefs.errors.wrap.label)); + } + } + } - ordereds.shift(); - continue; - } + return parts.join(''); + } - // Exclusions + _ref(content, { raw, wrapped }) { - const ancestors = [value, ...state.ancestors]; + const refs = []; + const reference = (variable) => { - for (const exclusion of schema.$_terms._exclusions) { - if (!exclusion.$_match(item, state.localize(path, ancestors, exclusion), prefs, { presence: 'ignore' })) { - continue; - } + const ref = Ref.create(variable, this._settings); + refs.push(ref); + return (context) => { - errors.push(error('array.excludes', { pos: i, value: item }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } + const resolved = ref.resolve(...context); + return resolved !== undefined ? resolved : null; + }; + }; - errored = true; - ordereds.shift(); - break; - } + try { + const functions = this._functions ? { ...internals.functions, ...this._functions } : internals.functions; + var formula = new Formula.Parser(content, { reference, functions, constants: internals.constants }); + } + catch (err) { + err.message = `Invalid template variable "${content}" fails due to: ${err.message}`; + throw err; + } - if (errored) { - continue; - } + if (formula.single) { + if (formula.single.type === 'reference') { + const ref = refs[0]; + return { ref, raw, refs, wrapped: wrapped || ref.type === 'local' && ref.key === 'label' }; + } - // Ordered + return internals.stringify(formula.single.value); + } - if (schema.$_terms.ordered.length) { - if (ordereds.length) { - const ordered = ordereds.shift(); - const res = ordered.$_validate(item, state.localize(path, ancestors, ordered), prefs); - if (!res.errors) { - if (ordered._flags.result === 'strip') { - internals.fastSplice(value, i); - --i; - --il; - } - else if (!schema._flags.sparse && res.value === undefined) { - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } + return { formula, raw, refs }; + } - continue; - } - else { - value[i] = res.value; - } - } - else { - errors.push(...res.errors); - if (prefs.abortEarly) { - return errors; - } - } + toString() { - continue; - } - else if (!schema.$_terms.items.length) { - errors.push(error('array.orderedLength', { pos: i, limit: schema.$_terms.ordered.length })); - if (prefs.abortEarly) { - return errors; - } + return this.source; + } +}; - break; // No reason to continue since there are no other rules to validate other than array.orderedLength - } - } - // Requireds +internals.Template.prototype[Common.symbols.template] = true; +internals.Template.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects - const requiredChecks = []; - let jl = requireds.length; - for (let j = 0; j < jl; ++j) { - const localState = state.localize(path, ancestors, requireds[j]); - localState.snapshot(); - const res = requireds[j].$_validate(item, localState, prefs); - requiredChecks[j] = res; +internals.encode = function (string) { - if (!res.errors) { - localState.commit(); - value[i] = res.value; - isValid = true; - internals.fastSplice(requireds, j); - --j; - --jl; + return string + .replace(/\\(\{+)/g, ($0, $1) => { - if (!schema._flags.sparse && - res.value === undefined) { + return internals.opens.slice(0, $1.length); + }) + .replace(/\\(\}+)/g, ($0, $1) => { - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } - } + return internals.closes.slice(0, $1.length); + }); +}; - break; - } - localState.restore(); - } +internals.decode = function (string) { + + return string + .replace(/\u0000/g, '{') + .replace(/\u0001/g, '}'); +}; + + +internals.split = function (string) { + + const parts = []; + let current = ''; + + for (let i = 0; i < string.length; ++i) { + const char = string[i]; + + if (char === '{') { + let next = ''; + while (i + 1 < string.length && + string[i + 1] === '{') { + + next += '{'; + ++i; + } - if (isValid) { - continue; - } + parts.push(current); + current = next; + } + else { + current += char; + } + } - // Inclusions + parts.push(current); + return parts; +}; - const stripUnknown = prefs.stripUnknown && !!prefs.stripUnknown.arrays || false; - jl = inclusions.length; - for (const inclusion of inclusions) { +internals.wrap = function (value, ends) { - // Avoid re-running requireds that already didn't match in the previous loop + if (!ends) { + return value; + } - let res; - const previousCheck = requireds.indexOf(inclusion); - if (previousCheck !== -1) { - res = requiredChecks[previousCheck]; - } - else { - const localState = state.localize(path, ancestors, inclusion); - localState.snapshot(); + if (ends.length === 1) { + return `${ends}${value}${ends}`; + } - res = inclusion.$_validate(item, localState, prefs); - if (!res.errors) { - localState.commit(); - if (inclusion._flags.result === 'strip') { - internals.fastSplice(value, i); - --i; - --il; - } - else if (!schema._flags.sparse && - res.value === undefined) { + return `${ends[0]}${value}${ends[1]}`; +}; - errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); - errored = true; - } - else { - value[i] = res.value; - } - isValid = true; - break; - } +internals.stringify = function (value, original, state, prefs, local, options = {}) { - localState.restore(); - } + const type = typeof value; + const wrap = prefs && prefs.errors && prefs.errors.wrap || {}; - // Return the actual error if only one inclusion defined + let skipWrap = false; + if (Ref.isRef(value) && + value.render) { - if (jl === 1) { - if (stripUnknown) { - internals.fastSplice(value, i); - --i; - --il; - isValid = true; - break; - } + skipWrap = value.in; + value = value.resolve(original, state, prefs, local, { in: value.in, ...options }); + } - errors.push(...res.errors); - if (prefs.abortEarly) { - return errors; - } + if (value === null) { + return 'null'; + } - errored = true; - break; - } - } + if (type === 'string') { + return internals.wrap(value, options.arrayItems && wrap.string); + } - if (errored) { - continue; - } + if (type === 'number' || + type === 'function' || + type === 'symbol') { - if ((schema.$_terms._inclusions.length || schema.$_terms._requireds.length) && - !isValid) { + return value.toString(); + } - if (stripUnknown) { - internals.fastSplice(value, i); - --i; - --il; - continue; - } + if (type !== 'object') { + return JSON.stringify(value); + } - errors.push(error('array.includes', { pos: i, value: item }, state.localize(path))); - if (prefs.abortEarly) { - return errors; - } - } - } + if (value instanceof Date) { + return internals.Template.date(value, prefs); + } - if (requireds.length) { - internals.fillMissedErrors(schema, errors, requireds, value, state, prefs); - } + if (value instanceof Map) { + const pairs = []; + for (const [key, sym] of value.entries()) { + pairs.push(`${key.toString()} -> ${sym.toString()}`); + } - if (ordereds.length) { - internals.fillOrderedErrors(schema, errors, ordereds, value, state, prefs); + value = pairs; + } - if (!errors.length) { - internals.fillDefault(ordereds, value, state, prefs); - } - } + if (!Array.isArray(value)) { + return value.toString(); + } - return errors.length ? errors : value; - }, + const values = []; + for (const item of value) { + values.push(internals.stringify(item, original, state, prefs, local, { arrayItems: true, ...options })); + } - priority: true, - manifest: false - }, + return internals.wrap(values.join(', '), !skipWrap && wrap.array); +}; - length: { - method(limit) { - return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); - }, - validate(value, helpers, { limit }, { name, operator, args }) { +internals.constants = { - if (Common.compare(value.length, limit, operator)) { - return value; - } + true: true, + false: false, + null: null, - return helpers.error('array.' + name, { limit: args.limit, value }); - }, - args: [ - { - name: 'limit', - ref: true, - assert: Common.limit, - message: 'must be a positive integer' - } - ] - }, + second: 1000, + minute: 60 * 1000, + hour: 60 * 60 * 1000, + day: 24 * 60 * 60 * 1000 +}; - max: { - method(limit) { - return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); - } - }, +internals.functions = { - min: { - method(limit) { + if(condition, then, otherwise) { - return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); - } - }, + return condition ? then : otherwise; + }, - ordered: { - method(...schemas) { + length(item) { - Common.verifyFlat(schemas, 'ordered'); + if (typeof item === 'string') { + return item.length; + } - const obj = this.$_addRule('items'); + if (!item || typeof item !== 'object') { + return null; + } - for (let i = 0; i < schemas.length; ++i) { - const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); - internals.validateSingle(type, obj); + if (Array.isArray(item)) { + return item.length; + } - obj.$_mutateRegister(type); - obj.$_terms.ordered.push(type); - } + return Object.keys(item).length; + }, - return obj.$_mutateRebuild(); - } - }, + msg(code) { - single: { - method(enabled) { + const [value, state, prefs, local, options] = this; + const messages = options.messages; + if (!messages) { + return ''; + } - const value = enabled === undefined ? true : !!enabled; - Assert(!value || !this._flags._arrayItems, 'Cannot specify single rule when array has array items'); + const template = Errors.template(value, messages[0], code, state, prefs) || Errors.template(value, messages[1], code, state, prefs); + if (!template) { + return ''; + } - return this.$_setFlag('single', value); - } - }, + return template.render(value, state, prefs, local, options); + }, - sort: { - method(options = {}) { + number(value) { - Common.assertOptions(options, ['by', 'order']); + if (typeof value === 'number') { + return value; + } - const settings = { - order: options.order || 'ascending' - }; + if (typeof value === 'string') { + return parseFloat(value); + } - if (options.by) { - settings.by = Compile.ref(options.by, { ancestor: 0 }); - Assert(!settings.by.ancestor, 'Cannot sort by ancestor'); - } + if (typeof value === 'boolean') { + return value ? 1 : 0; + } - return this.$_addRule({ name: 'sort', args: { options: settings } }); - }, - validate(value, { error, state, prefs, schema }, { options }) { + if (value instanceof Date) { + return value.getTime(); + } - const { value: sorted, errors } = internals.sort(schema, value, options, state, prefs); - if (errors) { - return errors; - } + return null; + } +}; - for (let i = 0; i < value.length; ++i) { - if (value[i] !== sorted[i]) { - return error('array.sort', { order: options.order, by: options.by ? options.by.key : 'value' }); - } - } - return value; - }, - convert: true - }, +/***/ }), - sparse: { - method(enabled) { +/***/ 43171: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const value = enabled === undefined ? true : !!enabled; +"use strict"; - if (this._flags.sparse === value) { - return this; - } - const obj = value ? this.clone() : this.$_addRule('items'); - return obj.$_setFlag('sparse', value, { clone: false }); - } - }, +const DeepEqual = __nccwpck_require__(55801); +const Pinpoint = __nccwpck_require__(75604); - unique: { - method(comparator, options = {}) { +const Errors = __nccwpck_require__(69490); - Assert(!comparator || typeof comparator === 'function' || typeof comparator === 'string', 'comparator must be a function or a string'); - Common.assertOptions(options, ['ignoreUndefined', 'separator']); - const rule = { name: 'unique', args: { options, comparator } }; +const internals = { + codes: { + error: 1, + pass: 2, + full: 3 + }, + labels: { + 0: 'never used', + 1: 'always error', + 2: 'always pass' + } +}; - if (comparator) { - if (typeof comparator === 'string') { - const separator = Common.default(options.separator, '.'); - rule.path = separator ? comparator.split(separator) : [comparator]; - } - else { - rule.comparator = comparator; - } - } - return this.$_addRule(rule); - }, - validate(value, { state, error, schema }, { comparator: raw, options }, { comparator, path }) { +exports.setup = function (root) { - const found = { - string: Object.create(null), - number: Object.create(null), - undefined: Object.create(null), - boolean: Object.create(null), - object: new Map(), - function: new Map(), - custom: new Map() - }; + const trace = function () { - const compare = comparator || DeepEqual; - const ignoreUndefined = options.ignoreUndefined; + root._tracer = root._tracer || new internals.Tracer(); + return root._tracer; + }; - for (let i = 0; i < value.length; ++i) { - const item = path ? Reach(value[i], path) : value[i]; - const records = comparator ? found.custom : found[typeof item]; - Assert(records, 'Failed to find unique map container for type', typeof item); + root.trace = trace; + root[Symbol.for('@hapi/lab/coverage/initialize')] = trace; - if (records instanceof Map) { - const entries = records.entries(); - let current; - while (!(current = entries.next()).done) { - if (compare(current.value[0], item)) { - const localState = state.localize([...state.path, i], [value, ...state.ancestors]); - const context = { - pos: i, - value: value[i], - dupePos: current.value[1], - dupeValue: value[current.value[1]] - }; + root.untrace = () => { - if (path) { - context.path = raw; - } + root._tracer = null; + }; +}; - return error('array.unique', context, localState); - } - } - records.set(item, i); - } - else { - if ((!ignoreUndefined || item !== undefined) && - records[item] !== undefined) { +exports.location = function (schema) { - const context = { - pos: i, - value: value[i], - dupePos: records[item], - dupeValue: value[records[item]] - }; + return schema.$_setFlag('_tracerLocation', Pinpoint.location(2)); // base.tracer(), caller +}; - if (path) { - context.path = raw; - } - const localState = state.localize([...state.path, i], [value, ...state.ancestors]); - return error('array.unique', context, localState); - } +internals.Tracer = class { - records[item] = i; - } - } + constructor() { - return value; - }, - args: ['comparator', 'options'], - multi: true - } - }, + this.name = 'Joi'; + this._schemas = new Map(); + } - cast: { - set: { - from: Array.isArray, - to(value, helpers) { + _register(schema) { - return new Set(value); - } + const existing = this._schemas.get(schema); + if (existing) { + return existing.store; } - }, - - rebuild(schema) { - schema.$_terms._inclusions = []; - schema.$_terms._exclusions = []; - schema.$_terms._requireds = []; + const store = new internals.Store(schema); + const { filename, line } = schema._flags._tracerLocation || Pinpoint.location(5); // internals.tracer(), internals.entry(), exports.entry(), validate(), caller + this._schemas.set(schema, { filename, line, store }); + return store; + } - for (const type of schema.$_terms.items) { - internals.validateSingle(type, schema); + _combine(merged, sources) { - if (type._flags.presence === 'required') { - schema.$_terms._requireds.push(type); - } - else if (type._flags.presence === 'forbidden') { - schema.$_terms._exclusions.push(type); - } - else { - schema.$_terms._inclusions.push(type); - } + for (const { store } of this._schemas.values()) { + store._combine(merged, sources); } + } - for (const type of schema.$_terms.ordered) { - internals.validateSingle(type, schema); - } - }, + report(file) { - manifest: { + const coverage = []; - build(obj, desc) { + // Process each registered schema - if (desc.items) { - obj = obj.items(...desc.items); - } + for (const { filename, line, store } of this._schemas.values()) { + if (file && + file !== filename) { - if (desc.ordered) { - obj = obj.ordered(...desc.ordered); + continue; } - return obj; - } - }, + // Process sub schemas of the registered root - messages: { - 'array.base': '{{#label}} must be an array', - 'array.excludes': '{{#label}} contains an excluded value', - 'array.hasKnown': '{{#label}} does not contain at least one required match for type {:#patternLabel}', - 'array.hasUnknown': '{{#label}} does not contain at least one required match', - 'array.includes': '{{#label}} does not match any of the allowed types', - 'array.includesRequiredBoth': '{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)', - 'array.includesRequiredKnowns': '{{#label}} does not contain {{#knownMisses}}', - 'array.includesRequiredUnknowns': '{{#label}} does not contain {{#unknownMisses}} required value(s)', - 'array.length': '{{#label}} must contain {{#limit}} items', - 'array.max': '{{#label}} must contain less than or equal to {{#limit}} items', - 'array.min': '{{#label}} must contain at least {{#limit}} items', - 'array.orderedLength': '{{#label}} must contain at most {{#limit}} items', - 'array.sort': '{{#label}} must be sorted in {#order} order by {{#by}}', - 'array.sort.mismatching': '{{#label}} cannot be sorted due to mismatching types', - 'array.sort.unsupported': '{{#label}} cannot be sorted due to unsupported type {#type}', - 'array.sparse': '{{#label}} must not be a sparse array item', - 'array.unique': '{{#label}} contains a duplicate value' - } -}); + const missing = []; + const skipped = []; + for (const [schema, log] of store._sources.entries()) { -// Helpers + // Check if sub schema parent skipped -internals.fillMissedErrors = function (schema, errors, requireds, value, state, prefs) { + if (internals.sub(log.paths, skipped)) { + continue; + } - const knownMisses = []; - let unknownMisses = 0; - for (const required of requireds) { - const label = required._flags.label; - if (label) { - knownMisses.push(label); - } - else { - ++unknownMisses; - } - } + // Check if sub schema reached - if (knownMisses.length) { - if (unknownMisses) { - errors.push(schema.$_createError('array.includesRequiredBoth', value, { knownMisses, unknownMisses }, state, prefs)); - } - else { - errors.push(schema.$_createError('array.includesRequiredKnowns', value, { knownMisses }, state, prefs)); - } - } - else { - errors.push(schema.$_createError('array.includesRequiredUnknowns', value, { unknownMisses }, state, prefs)); - } -}; + if (!log.entry) { + missing.push({ + status: 'never reached', + paths: [...log.paths] + }); + skipped.push(...log.paths); + continue; + } -internals.fillOrderedErrors = function (schema, errors, ordereds, value, state, prefs) { + // Check values - const requiredOrdereds = []; + for (const type of ['valid', 'invalid']) { + const set = schema[`_${type}s`]; + if (!set) { + continue; + } - for (const ordered of ordereds) { - if (ordered._flags.presence === 'required') { - requiredOrdereds.push(ordered); - } - } + const values = new Set(set._values); + const refs = new Set(set._refs); + for (const { value, ref } of log[type]) { + values.delete(value); + refs.delete(ref); + } - if (requiredOrdereds.length) { - internals.fillMissedErrors(schema, errors, requiredOrdereds, value, state, prefs); - } -}; + if (values.size || + refs.size) { + missing.push({ + status: [...values, ...[...refs].map((ref) => ref.display)], + rule: `${type}s` + }); + } + } -internals.fillDefault = function (ordereds, value, state, prefs) { + // Check rules status - const overrides = []; - let trailingUndefined = true; + const rules = schema._rules.map((rule) => rule.name); + for (const type of ['default', 'failover']) { + if (schema._flags[type] !== undefined) { + rules.push(type); + } + } - for (let i = ordereds.length - 1; i >= 0; --i) { - const ordered = ordereds[i]; - const ancestors = [value, ...state.ancestors]; - const override = ordered.$_validate(undefined, state.localize(state.path, ancestors, ordered), prefs).value; + for (const name of rules) { + const status = internals.labels[log.rule[name] || 0]; + if (status) { + const report = { rule: name, status }; + if (log.paths.size) { + report.paths = [...log.paths]; + } - if (trailingUndefined) { - if (override === undefined) { - continue; + missing.push(report); + } + } } - trailingUndefined = false; + if (missing.length) { + coverage.push({ + filename, + line, + missing, + severity: 'error', + message: `Schema missing tests for ${missing.map(internals.message).join(', ')}` + }); + } } - overrides.unshift(override); - } - - if (overrides.length) { - value.push(...overrides); + return coverage.length ? coverage : null; } }; -internals.fastSplice = function (arr, i) { - - let pos = i; - while (pos < arr.length) { - arr[pos++] = arr[pos]; - } - - --arr.length; -}; +internals.Store = class { + constructor(schema) { -internals.validateSingle = function (type, obj) { + this.active = true; + this._sources = new Map(); // schema -> { paths, entry, rule, valid, invalid } + this._combos = new Map(); // merged -> [sources] + this._scan(schema); + } - if (type.type === 'array' || - type._flags._arrayItems) { + debug(state, source, name, result) { - Assert(!obj._flags.single, 'Cannot specify array item with single rule enabled'); - obj.$_setFlag('_arrayItems', true, { clone: false }); + state.mainstay.debug && state.mainstay.debug.push({ type: source, name, result, path: state.path }); } -}; + entry(schema, state) { -internals.sort = function (schema, value, settings, state, prefs) { - - const order = settings.order === 'ascending' ? 1 : -1; - const aFirst = -1 * order; - const bFirst = order; + internals.debug(state, { type: 'entry' }); - const sort = (a, b) => { + this._record(schema, (log) => { - let compare = internals.compare(a, b, aFirst, bFirst); - if (compare !== null) { - return compare; - } + log.entry = true; + }); + } - if (settings.by) { - a = settings.by.resolve(a, state, prefs); - b = settings.by.resolve(b, state, prefs); - } + filter(schema, state, source, value) { - compare = internals.compare(a, b, aFirst, bFirst); - if (compare !== null) { - return compare; - } + internals.debug(state, { type: source, ...value }); - const type = typeof a; - if (type !== typeof b) { - throw schema.$_createError('array.sort.mismatching', value, null, state, prefs); - } + this._record(schema, (log) => { - if (type !== 'number' && - type !== 'string') { + log[source].add(value); + }); + } - throw schema.$_createError('array.sort.unsupported', value, { type }, state, prefs); - } + log(schema, state, source, name, result) { - if (type === 'number') { - return (a - b) * order; - } + internals.debug(state, { type: source, name, result: result === 'full' ? 'pass' : result }); - return a < b ? aFirst : bFirst; - }; + this._record(schema, (log) => { - try { - return { value: value.slice().sort(sort) }; - } - catch (err) { - return { errors: err }; + log[source][name] = log[source][name] || 0; + log[source][name] |= internals.codes[result]; + }); } -}; - -internals.compare = function (a, b, aFirst, bFirst) { + resolve(state, ref, to) { - if (a === b) { - return 0; - } + if (!state.mainstay.debug) { + return; + } - if (a === undefined) { - return 1; // Always last regardless of sort order + const log = { type: 'resolve', ref: ref.display, to, path: state.path }; + state.mainstay.debug.push(log); } - if (b === undefined) { - return -1; // Always last regardless of sort order - } + value(state, by, from, to, name) { - if (a === null) { - return bFirst; - } + if (!state.mainstay.debug || + DeepEqual(from, to)) { - if (b === null) { - return aFirst; - } + return; + } - return null; -}; + const log = { type: 'value', by, from, to, path: state.path }; + if (name) { + log.name = name; + } + state.mainstay.debug.push(log); + } -/***/ }), + _record(schema, each) { -/***/ 34288: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const log = this._sources.get(schema); + if (log) { + each(log); + return; + } -"use strict"; + const sources = this._combos.get(schema); + for (const source of sources) { + this._record(source, each); + } + } + _scan(schema, _path) { -const Assert = __nccwpck_require__(32718); + const path = _path || []; -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); + let log = this._sources.get(schema); + if (!log) { + log = { + paths: new Set(), + entry: false, + rule: {}, + valid: new Set(), + invalid: new Set() + }; + this._sources.set(schema, log); + } -const internals = {}; + if (path.length) { + log.paths.add(path); + } + const each = (sub, source) => { -module.exports = Any.extend({ + const subId = internals.id(sub, source); + this._scan(sub, path.concat(subId)); + }; - type: 'binary', + schema.$_modify({ each, ref: false }); + } - coerce: { - from: ['string', 'object'], - method(value, { schema }) { + _combine(merged, sources) { - if (typeof value === 'string' || (value !== null && value.type === 'Buffer')) { - try { - return { value: Buffer.from(value, schema._flags.encoding) }; - } - catch (ignoreErr) { } - } - } - }, + this._combos.set(merged, sources); + } +}; - validate(value, { error }) { - if (!Buffer.isBuffer(value)) { - return { value, errors: error('binary.base') }; - } - }, +internals.message = function (item) { - rules: { - encoding: { - method(encoding) { + const path = item.paths ? Errors.path(item.paths[0]) + (item.rule ? ':' : '') : ''; + return `${path}${item.rule || ''} (${item.status})`; +}; - Assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); - return this.$_setFlag('encoding', encoding); - } - }, +internals.id = function (schema, { source, name, path, key }) { - length: { - method(limit) { + if (schema._flags.id) { + return schema._flags.id; + } - return this.$_addRule({ name: 'length', method: 'length', args: { limit }, operator: '=' }); - }, - validate(value, helpers, { limit }, { name, operator, args }) { + if (key) { + return key; + } - if (Common.compare(value.length, limit, operator)) { - return value; - } + name = `@${name}`; - return helpers.error('binary.' + name, { limit: args.limit, value }); - }, - args: [ - { - name: 'limit', - ref: true, - assert: Common.limit, - message: 'must be a positive integer' - } - ] - }, + if (source === 'terms') { + return [name, path[Math.min(path.length - 1, 1)]]; + } - max: { - method(limit) { + return name; +}; - return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); - } - }, - min: { - method(limit) { +internals.sub = function (paths, skipped) { - return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); + for (const path of paths) { + for (const skip of skipped) { + if (DeepEqual(path.slice(0, skip.length), skip)) { + return true; } } - }, + } - cast: { - string: { - from: (value) => Buffer.isBuffer(value), - to(value, helpers) { + return false; +}; - return value.toString(); - } - } - }, - messages: { - 'binary.base': '{{#label}} must be a buffer or a string', - 'binary.length': '{{#label}} must be {{#limit}} bytes', - 'binary.max': '{{#label}} must be less than or equal to {{#limit}} bytes', - 'binary.min': '{{#label}} must be at least {{#limit}} bytes' +internals.debug = function (state, event) { + + if (state.mainstay.debug) { + event.path = state.debug ? [...state.path, state.debug] : state.path; + state.mainstay.debug.push(event); } -}); +}; /***/ }), -/***/ 47489: +/***/ 26867: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Assert = __nccwpck_require__(32718); +const Merge = __nccwpck_require__(60445); const Any = __nccwpck_require__(9512); const Common = __nccwpck_require__(72448); -const Values = __nccwpck_require__(71944); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Ref = __nccwpck_require__(73838); const internals = {}; -internals.isBool = function (value) { - - return typeof value === 'boolean'; -}; - - module.exports = Any.extend({ - type: 'boolean', + type: 'alternatives', flags: { - sensitive: { default: false } + match: { default: 'any' } // 'any', 'one', 'all' }, terms: { - falsy: { - init: null, - manifest: 'values' - }, - - truthy: { - init: null, - manifest: 'values' - } + matches: { init: [], register: Ref.toSibling } }, - coerce(value, { schema }) { - - if (typeof value === 'boolean') { - return; - } - - if (typeof value === 'string') { - const normalized = schema._flags.sensitive ? value : value.toLowerCase(); - value = normalized === 'true' ? true : (normalized === 'false' ? false : value); - } + args(schema, ...schemas) { - if (typeof value !== 'boolean') { - value = schema.$_terms.truthy && schema.$_terms.truthy.has(value, null, null, !schema._flags.sensitive) || - (schema.$_terms.falsy && schema.$_terms.falsy.has(value, null, null, !schema._flags.sensitive) ? false : value); + if (schemas.length === 1) { + if (Array.isArray(schemas[0])) { + return schema.try(...schemas[0]); + } } - return { value }; + return schema.try(...schemas); }, - validate(value, { error }) { - - if (typeof value !== 'boolean') { - return { value, errors: error('boolean.base') }; - } - }, + validate(value, helpers) { - rules: { - truthy: { - method(...values) { + const { schema, error, state, prefs } = helpers; - Common.verifyFlat(values, 'truthy'); + // Match all or one - const obj = this.clone(); - obj.$_terms.truthy = obj.$_terms.truthy || new Values(); + if (schema._flags.match) { + const matched = []; + const failed = []; - for (let i = 0; i < values.length; ++i) { - const value = values[i]; + for (let i = 0; i < schema.$_terms.matches.length; ++i) { + const item = schema.$_terms.matches[i]; + const localState = state.nest(item.schema, `match.${i}`); + localState.snapshot(); - Assert(value !== undefined, 'Cannot call truthy with undefined'); - obj.$_terms.truthy.add(value); + const result = item.schema.$_validate(value, localState, prefs); + if (!result.errors) { + matched.push(result.value); + localState.commit(); } - - return obj; - } - }, - - falsy: { - method(...values) { - - Common.verifyFlat(values, 'falsy'); - - const obj = this.clone(); - obj.$_terms.falsy = obj.$_terms.falsy || new Values(); - - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Assert(value !== undefined, 'Cannot call falsy with undefined'); - obj.$_terms.falsy.add(value); + else { + failed.push(result.errors); + localState.restore(); } - - return obj; } - }, - sensitive: { - method(enabled = true) { + if (matched.length === 0) { + const context = { + details: failed.map((f) => Errors.details(f, { override: false })) + }; - return this.$_setFlag('sensitive', enabled); + return { errors: error('alternatives.any', context) }; } - } - }, - cast: { - number: { - from: internals.isBool, - to(value, helpers) { - - return value ? 1 : 0; - } - }, - string: { - from: internals.isBool, - to(value, helpers) { + // Match one - return value ? 'true' : 'false'; + if (schema._flags.match === 'one') { + return matched.length === 1 ? { value: matched[0] } : { errors: error('alternatives.one') }; } - } - }, - - manifest: { - build(obj, desc) { + // Match all - if (desc.truthy) { - obj = obj.truthy(...desc.truthy); - } + if (matched.length !== schema.$_terms.matches.length) { + const context = { + details: failed.map((f) => Errors.details(f, { override: false })) + }; - if (desc.falsy) { - obj = obj.falsy(...desc.falsy); + return { errors: error('alternatives.all', context) }; } - return obj; - } - }, - - messages: { - 'boolean.base': '{{#label}} must be a boolean' - } -}); - - -/***/ }), - -/***/ 6624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); - -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Template = __nccwpck_require__(51396); - - -const internals = {}; - + const isAnyObj = (alternative) => { -internals.isDate = function (value) { + return alternative.$_terms.matches.some((v) => { - return value instanceof Date; -}; + return v.schema.type === 'object' || + (v.schema.type === 'alternatives' && isAnyObj(v.schema)); + }); + }; + return isAnyObj(schema) ? { value: matched.reduce((acc, v) => Merge(acc, v, { mergeArrays: false })) } : { value: matched[matched.length - 1] }; + } -module.exports = Any.extend({ + // Match any - type: 'date', + const errors = []; + for (let i = 0; i < schema.$_terms.matches.length; ++i) { + const item = schema.$_terms.matches[i]; - coerce: { - from: ['number', 'string'], - method(value, { schema }) { + // Try - return { value: internals.parse(value, schema._flags.format) || value }; - } - }, + if (item.schema) { + const localState = state.nest(item.schema, `match.${i}`); + localState.snapshot(); - validate(value, { schema, error, prefs }) { + const result = item.schema.$_validate(value, localState, prefs); + if (!result.errors) { + localState.commit(); + return result; + } - if (value instanceof Date && - !isNaN(value.getTime())) { + localState.restore(); + errors.push({ schema: item.schema, reports: result.errors }); + continue; + } - return; - } + // Conditional - const format = schema._flags.format; + const input = item.ref ? item.ref.resolve(value, state, prefs) : value; + const tests = item.is ? [item] : item.switch; - if (!prefs.convert || - !format || - typeof value !== 'string') { + for (let j = 0; j < tests.length; ++j) { + const test = tests[j]; + const { is, then, otherwise } = test; - return { value, errors: error('date.base') }; + const id = `match.${i}${item.switch ? '.' + j : ''}`; + if (!is.$_match(input, state.nest(is, `${id}.is`), prefs)) { + if (otherwise) { + return otherwise.$_validate(value, state.nest(otherwise, `${id}.otherwise`), prefs); + } + } + else if (then) { + return then.$_validate(value, state.nest(then, `${id}.then`), prefs); + } + } } - return { value, errors: error('date.format', { format }) }; + return internals.errors(errors, helpers); }, rules: { - compare: { - method: false, - validate(value, helpers, { date }, { name, operator, args }) { - - const to = date === 'now' ? Date.now() : date.getTime(); - if (Common.compare(value.getTime(), to, operator)) { - return value; - } + conditional: { + method(condition, options) { - return helpers.error('date.' + name, { limit: args.date, value }); - }, - args: [ - { - name: 'date', - ref: true, - normalize: (date) => { + Assert(!this._flags._endedSwitch, 'Unreachable condition'); + Assert(!this._flags.match, 'Cannot combine match mode', this._flags.match, 'with conditional rule'); + Assert(options.break === undefined, 'Cannot use break option with alternatives conditional'); - return date === 'now' ? date : internals.parse(date); - }, - assert: (date) => date !== null, - message: 'must have a valid date format' - } - ] - }, + const obj = this.clone(); - format: { - method(format) { + const match = Compile.when(obj, condition, options); + const conditions = match.is ? [match] : match.switch; + for (const item of conditions) { + if (item.then && + item.otherwise) { - Assert(['iso', 'javascript', 'unix'].includes(format), 'Unknown date format', format); + obj.$_setFlag('_endedSwitch', true, { clone: false }); + break; + } + } - return this.$_setFlag('format', format); + obj.$_terms.matches.push(match); + return obj.$_mutateRebuild(); } }, - greater: { - method(date) { + match: { + method(mode) { - return this.$_addRule({ name: 'greater', method: 'compare', args: { date }, operator: '>' }); - } - }, + Assert(['any', 'one', 'all'].includes(mode), 'Invalid alternatives match mode', mode); - iso: { - method() { + if (mode !== 'any') { + for (const match of this.$_terms.matches) { + Assert(match.schema, 'Cannot combine match mode', mode, 'with conditional rules'); + } + } - return this.format('iso'); + return this.$_setFlag('match', mode); } }, - less: { - method(date) { + try: { + method(...schemas) { - return this.$_addRule({ name: 'less', method: 'compare', args: { date }, operator: '<' }); - } - }, + Assert(schemas.length, 'Missing alternative schemas'); + Common.verifyFlat(schemas, 'try'); - max: { - method(date) { + Assert(!this._flags._endedSwitch, 'Unreachable condition'); - return this.$_addRule({ name: 'max', method: 'compare', args: { date }, operator: '<=' }); + const obj = this.clone(); + for (const schema of schemas) { + obj.$_terms.matches.push({ schema: obj.$_compile(schema) }); + } + + return obj.$_mutateRebuild(); } - }, + } + }, - min: { - method(date) { + overrides: { - return this.$_addRule({ name: 'min', method: 'compare', args: { date }, operator: '>=' }); - } - }, + label(name) { - timestamp: { - method(type = 'javascript') { + const obj = this.$_parent('label', name); + const each = (item, source) => { - Assert(['javascript', 'unix'].includes(type), '"type" must be one of "javascript, unix"'); + return source.path[0] !== 'is' && typeof item._flags.label !== 'string' ? item.label(name) : undefined; + }; - return this.format(type); - } + return obj.$_modify({ each, ref: false }); } }, - cast: { - number: { - from: internals.isDate, - to(value, helpers) { + rebuild(schema) { - return value.getTime(); + // Flag when an alternative type is an array + + const each = (item) => { + + if (Common.isSchema(item) && + item.type === 'array') { + + schema.$_setFlag('_arrayItems', true, { clone: false }); } - }, - string: { - from: internals.isDate, - to(value, { prefs }) { + }; - return Template.date(value, prefs); + schema.$_modify({ each }); + }, + + manifest: { + + build(obj, desc) { + + if (desc.matches) { + for (const match of desc.matches) { + const { schema, ref, is, not, then, otherwise } = match; + if (schema) { + obj = obj.try(schema); + } + else if (ref) { + obj = obj.conditional(ref, { is, then, not, otherwise, switch: match.switch }); + } + else { + obj = obj.conditional(is, { then, otherwise }); + } + } } + + return obj; } }, messages: { - 'date.base': '{{#label}} must be a valid date', - 'date.format': '{{#label}} must be in {msg("date.format." + #format) || #format} format', - 'date.greater': '{{#label}} must be greater than {{:#limit}}', - 'date.less': '{{#label}} must be less than {{:#limit}}', - 'date.max': '{{#label}} must be less than or equal to {{:#limit}}', - 'date.min': '{{#label}} must be greater than or equal to {{:#limit}}', - - // Messages used in date.format - - 'date.format.iso': 'ISO 8601 date', - 'date.format.javascript': 'timestamp or number of milliseconds', - 'date.format.unix': 'timestamp or number of seconds' + 'alternatives.all': '{{#label}} does not match all of the required types', + 'alternatives.any': '{{#label}} does not match any of the allowed types', + 'alternatives.match': '{{#label}} does not match any of the allowed types', + 'alternatives.one': '{{#label}} matches more than one allowed type', + 'alternatives.types': '{{#label}} must be one of {{#types}}' } }); // Helpers -internals.parse = function (value, format) { +internals.errors = function (failures, { error, state }) { - if (value instanceof Date) { - return value; + // Nothing matched due to type criteria rules + + if (!failures.length) { + return { errors: error('alternatives.any') }; } - if (typeof value !== 'string' && - (isNaN(value) || !isFinite(value))) { + // Single error - return null; + if (failures.length === 1) { + return { errors: failures[0].reports }; } - if (/^\s*$/.test(value)) { - return null; - } + // Analyze reasons - // ISO + const valids = new Set(); + const complex = []; - if (format === 'iso') { - if (!Common.isIsoDate(value)) { - return null; - } + for (const { reports, schema } of failures) { - return internals.date(value.toString()); - } + // Multiple errors (!abortEarly) - // Normalize number string + if (reports.length > 1) { + return internals.unmatched(failures, error); + } - const original = value; - if (typeof value === 'string' && - /^[+-]?\d+(\.\d+)?$/.test(value)) { + // Custom error - value = parseFloat(value); - } + const report = reports[0]; + if (report instanceof Errors.Report === false) { + return internals.unmatched(failures, error); + } - // Timestamp + // Internal object or array error - if (format) { - if (format === 'javascript') { - return internals.date(1 * value); // Casting to number + if (report.state.path.length !== state.path.length) { + complex.push({ type: schema.type, report }); + continue; } - if (format === 'unix') { - return internals.date(1000 * value); + // Valids + + if (report.code === 'any.only') { + for (const valid of report.local.valids) { + valids.add(valid); + } + + continue; } - if (typeof original === 'string') { - return null; + // Base type + + const [type, code] = report.code.split('.'); + if (code !== 'base') { + complex.push({ type: schema.type, report }); + } + else if (report.code === 'object.base') { + valids.add(report.local.type); + } + else { + valids.add(type); } } - // Plain + // All errors are base types or valids - return internals.date(value); + if (!complex.length) { + return { errors: error('alternatives.types', { types: [...valids] }) }; + } + + // Single complex error + + if (complex.length === 1) { + return { errors: complex[0].report }; + } + + return internals.unmatched(failures, error); }; -internals.date = function (value) { +internals.unmatched = function (failures, error) { - const date = new Date(value); - if (!isNaN(date.getTime())) { - return date; + const errors = []; + for (const failure of failures) { + errors.push(...failure.reports); } - return null; + return { errors: error('alternatives.match', Errors.details(errors, { override: false })) }; }; /***/ }), -/***/ 62269: +/***/ 9512: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -27516,1175 +27801,1106 @@ internals.date = function (value) { const Assert = __nccwpck_require__(32718); -const Keys = __nccwpck_require__(79130); +const Base = __nccwpck_require__(95184); +const Common = __nccwpck_require__(72448); +const Messages = __nccwpck_require__(86103); const internals = {}; -module.exports = Keys.extend({ +module.exports = Base.extend({ - type: 'function', + type: 'any', - properties: { - typeof: 'function' - }, + flags: { - rules: { - arity: { - method(n) { + only: { default: false } + }, - Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); + terms: { - return this.$_addRule({ name: 'arity', args: { n } }); - }, - validate(value, helpers, { n }) { + alterations: { init: null }, + examples: { init: null }, + externals: { init: null }, + metas: { init: [] }, + notes: { init: [] }, + shared: { init: null }, + tags: { init: [] }, + whens: { init: null } + }, - if (value.length === n) { - return value; - } + rules: { - return helpers.error('function.arity', { n }); - } - }, + custom: { + method(method, description) { - class: { - method() { + Assert(typeof method === 'function', 'Method must be a function'); + Assert(description === undefined || description && typeof description === 'string', 'Description must be a non-empty string'); - return this.$_addRule('class'); + return this.$_addRule({ name: 'custom', args: { method, description } }); }, - validate(value, helpers) { + validate(value, helpers, { method }) { - if ((/^\s*class\s/).test(value.toString())) { - return value; + try { + return method(value, helpers); } - - return helpers.error('function.class', { value }); - } + catch (err) { + return helpers.error('any.custom', { error: err }); + } + }, + args: ['method', 'description'], + multi: true }, - minArity: { - method(n) { + messages: { + method(messages) { - Assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer'); + return this.prefs({ messages }); + } + }, - return this.$_addRule({ name: 'minArity', args: { n } }); - }, - validate(value, helpers, { n }) { + shared: { + method(schema) { - if (value.length >= n) { - return value; - } + Assert(Common.isSchema(schema) && schema._flags.id, 'Schema must be a schema with an id'); - return helpers.error('function.minArity', { n }); + const obj = this.clone(); + obj.$_terms.shared = obj.$_terms.shared || []; + obj.$_terms.shared.push(schema); + obj.$_mutateRegister(schema); + return obj; } }, - maxArity: { - method(n) { + warning: { + method(code, local) { - Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); + Assert(code && typeof code === 'string', 'Invalid warning code'); - return this.$_addRule({ name: 'maxArity', args: { n } }); + return this.$_addRule({ name: 'warning', args: { code, local }, warn: true }); }, - validate(value, helpers, { n }) { - - if (value.length <= n) { - return value; - } + validate(value, helpers, { code, local }) { - return helpers.error('function.maxArity', { n }); - } + return helpers.error(code, local); + }, + args: ['code', 'local'], + multi: true } }, - messages: { - 'function.arity': '{{#label}} must have an arity of {{#n}}', - 'function.class': '{{#label}} must be a class', - 'function.maxArity': '{{#label}} must have an arity lesser or equal to {{#n}}', - 'function.minArity': '{{#label}} must have an arity greater or equal to {{#n}}' - } -}); - - -/***/ }), - -/***/ 79130: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const ApplyToDefaults = __nccwpck_require__(85545); -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Topo = __nccwpck_require__(88392); - -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); -const Ref = __nccwpck_require__(73838); -const Template = __nccwpck_require__(51396); - + modifiers: { -const internals = { - renameDefaults: { - alias: false, // Keep old value in place - multiple: false, // Allow renaming multiple keys into the same target - override: false // Overrides an existing key - } -}; + keep(rule, enabled = true) { + rule.keep = enabled; + }, -module.exports = Any.extend({ + message(rule, message) { - type: '_keys', + rule.message = Messages.compile(message); + }, - properties: { + warn(rule, enabled = true) { - typeof: 'object' + rule.warn = enabled; + } }, - flags: { - - unknown: { default: false } - }, + manifest: { - terms: { + build(obj, desc) { - dependencies: { init: null }, - keys: { init: null, manifest: { mapped: { from: 'schema', to: 'key' } } }, - patterns: { init: null }, - renames: { init: null } - }, + for (const key in desc) { + const values = desc[key]; - args(schema, keys) { + if (['examples', 'externals', 'metas', 'notes', 'tags'].includes(key)) { + for (const value of values) { + obj = obj[key.slice(0, -1)](value); + } - return schema.keys(keys); - }, + continue; + } - validate(value, { schema, error, state, prefs }) { + if (key === 'alterations') { + const alter = {}; + for (const { target, adjuster } of values) { + alter[target] = adjuster; + } - if (!value || - typeof value !== schema.$_property('typeof') || - Array.isArray(value)) { + obj = obj.alter(alter); + continue; + } - return { value, errors: error('object.base', { type: schema.$_property('typeof') }) }; - } + if (key === 'whens') { + for (const value of values) { + const { ref, is, not, then, otherwise, concat } = value; + if (concat) { + obj = obj.concat(concat); + } + else if (ref) { + obj = obj.when(ref, { is, not, then, otherwise, switch: value.switch, break: value.break }); + } + else { + obj = obj.when(is, { then, otherwise, break: value.break }); + } + } - // Skip if there are no other rules to test + continue; + } - if (!schema.$_terms.renames && - !schema.$_terms.dependencies && - !schema.$_terms.keys && // null allows any keys - !schema.$_terms.patterns && - !schema.$_terms.externals) { + if (key === 'shared') { + for (const value of values) { + obj = obj.shared(value); + } + } + } - return; + return obj; } + }, - // Shallow clone value + messages: { + 'any.custom': '{{#label}} failed custom validation because {{#error.message}}', + 'any.default': '{{#label}} threw an error when running default method', + 'any.failover': '{{#label}} threw an error when running failover method', + 'any.invalid': '{{#label}} contains an invalid value', + 'any.only': '{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}', + 'any.ref': '{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}', + 'any.required': '{{#label}} is required', + 'any.unknown': '{{#label}} is not allowed' + } +}); - value = internals.clone(value, prefs); - const errors = []; - // Rename keys +/***/ }), - if (schema.$_terms.renames && - !internals.rename(schema, value, state, prefs, errors)) { +/***/ 20270: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return { value, errors }; - } +"use strict"; - // Anything allowed - if (!schema.$_terms.keys && // null allows any keys - !schema.$_terms.patterns && - !schema.$_terms.dependencies) { +const Assert = __nccwpck_require__(32718); +const DeepEqual = __nccwpck_require__(55801); +const Reach = __nccwpck_require__(18891); - return { value, errors }; - } +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); - // Defined keys - const unprocessed = new Set(Object.keys(value)); +const internals = {}; - if (schema.$_terms.keys) { - const ancestors = [value, ...state.ancestors]; - for (const child of schema.$_terms.keys) { - const key = child.key; - const item = value[key]; +module.exports = Any.extend({ - unprocessed.delete(key); + type: 'array', - const localState = state.localize([...state.path, key], ancestors, child); - const result = child.schema.$_validate(item, localState, prefs); + flags: { - if (result.errors) { - if (prefs.abortEarly) { - return { value, errors: result.errors }; - } + single: { default: false }, + sparse: { default: false } + }, - if (result.value !== undefined) { - value[key] = result.value; - } + terms: { - errors.push(...result.errors); - } - else if (child.schema._flags.result === 'strip' || - result.value === undefined && item !== undefined) { + items: { init: [], manifest: 'schema' }, + ordered: { init: [], manifest: 'schema' }, - delete value[key]; - } - else if (result.value !== undefined) { - value[key] = result.value; - } - } - } + _exclusions: { init: [] }, + _inclusions: { init: [] }, + _requireds: { init: [] } + }, - // Unknown keys + coerce: { + from: 'object', + method(value, { schema, state, prefs }) { - if (unprocessed.size || - schema._flags._hasPatternMatch) { + if (!Array.isArray(value)) { + return; + } - const early = internals.unknown(schema, value, unprocessed, errors, state, prefs); - if (early) { - return early; + const sort = schema.$_getRule('sort'); + if (!sort) { + return; } + + return internals.sort(schema, value, sort.args.options, state, prefs); } + }, - // Validate dependencies + validate(value, { schema, error }) { - if (schema.$_terms.dependencies) { - for (const dep of schema.$_terms.dependencies) { - if ( - dep.key !== null && - internals.isPresent(dep.options)(dep.key.resolve(value, state, prefs, null, { shadow: false })) === false - ) { + if (!Array.isArray(value)) { + if (schema._flags.single) { + const single = [value]; + single[Common.symbols.arraySingle] = true; + return { value: single }; + } - continue; - } + return { errors: error('array.base') }; + } - const failed = internals.dependencies[dep.rel](schema, dep, value, state, prefs); - if (failed) { - const report = schema.$_createError(failed.code, value, failed.context, state, prefs); - if (prefs.abortEarly) { - return { value, errors: report }; - } + if (!schema.$_getRule('items') && + !schema.$_terms.externals) { - errors.push(report); - } - } + return; } - return { value, errors }; + return { value: value.slice() }; // Clone the array so that we don't modify the original }, rules: { - and: { - method(...peers /*, [options] */) { - - Common.verifyFlat(peers, 'and'); - - return internals.dependency(this, 'and', null, peers); - } - }, - - append: { + has: { method(schema) { - if (schema === null || - schema === undefined || - Object.keys(schema).length === 0) { - - return this; - } - - return this.keys(schema); - } - }, - - assert: { - method(subject, schema, message) { - - if (!Template.isTemplate(subject)) { - subject = Compile.ref(subject); - } - - Assert(message === undefined || typeof message === 'string', 'Message must be a string'); - schema = this.$_compile(schema, { appendPath: true }); - - const obj = this.$_addRule({ name: 'assert', args: { subject, schema, message } }); - obj.$_mutateRegister(subject); + const obj = this.$_addRule({ name: 'has', args: { schema } }); obj.$_mutateRegister(schema); return obj; }, - validate(value, { error, prefs, state }, { subject, schema, message }) { + validate(value, { state, prefs, error }, { schema: has }) { - const about = subject.resolve(value, state, prefs); - const path = Ref.isRef(subject) ? subject.absolute(state) : []; - if (schema.$_match(about, state.localize(path, [value, ...state.ancestors], schema), prefs)) { - return value; + const ancestors = [value, ...state.ancestors]; + for (let i = 0; i < value.length; ++i) { + const localState = state.localize([...state.path, i], ancestors, has); + if (has.$_match(value[i], localState, prefs)) { + return value; + } } - return error('object.assert', { subject, message }); + const patternLabel = has._flags.label; + if (patternLabel) { + return error('array.hasKnown', { patternLabel }); + } + + return error('array.hasUnknown', null); }, - args: ['subject', 'schema', 'message'], multi: true }, - instance: { - method(constructor, name) { - - Assert(typeof constructor === 'function', 'constructor must be a function'); + items: { + method(...schemas) { - name = name || constructor.name; + Common.verifyFlat(schemas, 'items'); - return this.$_addRule({ name: 'instance', args: { constructor, name } }); - }, - validate(value, helpers, { constructor, name }) { + const obj = this.$_addRule('items'); - if (value instanceof constructor) { - return value; + for (let i = 0; i < schemas.length; ++i) { + const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); + obj.$_terms.items.push(type); } - return helpers.error('object.instance', { type: name, value }); + return obj.$_mutateRebuild(); }, - args: ['constructor', 'name'] - }, + validate(value, { schema, error, state, prefs, errorsArray }) { - keys: { - method(schema) { + const requireds = schema.$_terms._requireds.slice(); + const ordereds = schema.$_terms.ordered.slice(); + const inclusions = [...schema.$_terms._inclusions, ...requireds]; - Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object'); - Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema'); + const wasArray = !value[Common.symbols.arraySingle]; + delete value[Common.symbols.arraySingle]; - const obj = this.clone(); + const errors = errorsArray(); - if (!schema) { // Allow all - obj.$_terms.keys = null; - } - else if (!Object.keys(schema).length) { // Allow none - obj.$_terms.keys = new internals.Keys(); - } - else { - obj.$_terms.keys = obj.$_terms.keys ? obj.$_terms.keys.filter((child) => !schema.hasOwnProperty(child.key)) : new internals.Keys(); - for (const key in schema) { - Common.tryWithPath(() => obj.$_terms.keys.push({ key, schema: this.$_compile(schema[key]) }), key); - } - } + let il = value.length; + for (let i = 0; i < il; ++i) { + const item = value[i]; - return obj.$_mutateRebuild(); - } - }, + let errored = false; + let isValid = false; - length: { - method(limit) { + const key = wasArray ? i : new Number(i); // eslint-disable-line no-new-wrappers + const path = [...state.path, key]; - return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); - }, - validate(value, helpers, { limit }, { name, operator, args }) { + // Sparse - if (Common.compare(Object.keys(value).length, limit, operator)) { - return value; - } + if (!schema._flags.sparse && + item === undefined) { - return helpers.error('object.' + name, { limit: args.limit, value }); - }, - args: [ - { - name: 'limit', - ref: true, - assert: Common.limit, - message: 'must be a positive integer' - } - ] - }, + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } - max: { - method(limit) { + ordereds.shift(); + continue; + } - return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); - } - }, + // Exclusions - min: { - method(limit) { + const ancestors = [value, ...state.ancestors]; - return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); - } - }, + for (const exclusion of schema.$_terms._exclusions) { + if (!exclusion.$_match(item, state.localize(path, ancestors, exclusion), prefs, { presence: 'ignore' })) { + continue; + } - nand: { - method(...peers /*, [options] */) { + errors.push(error('array.excludes', { pos: i, value: item }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } - Common.verifyFlat(peers, 'nand'); + errored = true; + ordereds.shift(); + break; + } - return internals.dependency(this, 'nand', null, peers); - } - }, + if (errored) { + continue; + } - or: { - method(...peers /*, [options] */) { + // Ordered - Common.verifyFlat(peers, 'or'); + if (schema.$_terms.ordered.length) { + if (ordereds.length) { + const ordered = ordereds.shift(); + const res = ordered.$_validate(item, state.localize(path, ancestors, ordered), prefs); + if (!res.errors) { + if (ordered._flags.result === 'strip') { + internals.fastSplice(value, i); + --i; + --il; + } + else if (!schema._flags.sparse && res.value === undefined) { + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } - return internals.dependency(this, 'or', null, peers); - } - }, + continue; + } + else { + value[i] = res.value; + } + } + else { + errors.push(...res.errors); + if (prefs.abortEarly) { + return errors; + } + } - oxor: { - method(...peers /*, [options] */) { + continue; + } + else if (!schema.$_terms.items.length) { + errors.push(error('array.orderedLength', { pos: i, limit: schema.$_terms.ordered.length })); + if (prefs.abortEarly) { + return errors; + } - return internals.dependency(this, 'oxor', null, peers); - } - }, + break; // No reason to continue since there are no other rules to validate other than array.orderedLength + } + } - pattern: { - method(pattern, schema, options = {}) { + // Requireds - const isRegExp = pattern instanceof RegExp; - if (!isRegExp) { - pattern = this.$_compile(pattern, { appendPath: true }); - } + const requiredChecks = []; + let jl = requireds.length; + for (let j = 0; j < jl; ++j) { + const localState = state.localize(path, ancestors, requireds[j]); + localState.snapshot(); - Assert(schema !== undefined, 'Invalid rule'); - Common.assertOptions(options, ['fallthrough', 'matches']); + const res = requireds[j].$_validate(item, localState, prefs); + requiredChecks[j] = res; - if (isRegExp) { - Assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); - } + if (!res.errors) { + localState.commit(); + value[i] = res.value; + isValid = true; + internals.fastSplice(requireds, j); + --j; + --jl; - schema = this.$_compile(schema, { appendPath: true }); + if (!schema._flags.sparse && + res.value === undefined) { - const obj = this.clone(); - obj.$_terms.patterns = obj.$_terms.patterns || []; - const config = { [isRegExp ? 'regex' : 'schema']: pattern, rule: schema }; - if (options.matches) { - config.matches = this.$_compile(options.matches); - if (config.matches.type !== 'array') { - config.matches = config.matches.$_root.array().items(config.matches); + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } + } + + break; + } + + localState.restore(); } - obj.$_mutateRegister(config.matches); - obj.$_setFlag('_hasPatternMatch', true, { clone: false }); - } + if (isValid) { + continue; + } - if (options.fallthrough) { - config.fallthrough = true; - } + // Inclusions - obj.$_terms.patterns.push(config); - obj.$_mutateRegister(schema); - return obj; - } - }, + const stripUnknown = prefs.stripUnknown && !!prefs.stripUnknown.arrays || false; - ref: { - method() { + jl = inclusions.length; + for (const inclusion of inclusions) { - return this.$_addRule('ref'); - }, - validate(value, helpers) { + // Avoid re-running requireds that already didn't match in the previous loop - if (Ref.isRef(value)) { - return value; - } + let res; + const previousCheck = requireds.indexOf(inclusion); + if (previousCheck !== -1) { + res = requiredChecks[previousCheck]; + } + else { + const localState = state.localize(path, ancestors, inclusion); + localState.snapshot(); - return helpers.error('object.refType', { value }); - } - }, + res = inclusion.$_validate(item, localState, prefs); + if (!res.errors) { + localState.commit(); + if (inclusion._flags.result === 'strip') { + internals.fastSplice(value, i); + --i; + --il; + } + else if (!schema._flags.sparse && + res.value === undefined) { - regex: { - method() { + errors.push(error('array.sparse', { key, path, pos: i, value: undefined }, state.localize(path))); + errored = true; + } + else { + value[i] = res.value; + } - return this.$_addRule('regex'); - }, - validate(value, helpers) { + isValid = true; + break; + } - if (value instanceof RegExp) { - return value; - } + localState.restore(); + } - return helpers.error('object.regex', { value }); - } - }, + // Return the actual error if only one inclusion defined - rename: { - method(from, to, options = {}) { + if (jl === 1) { + if (stripUnknown) { + internals.fastSplice(value, i); + --i; + --il; + isValid = true; + break; + } - Assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument'); - Assert(typeof to === 'string' || to instanceof Template, 'Invalid rename to argument'); - Assert(to !== from, 'Cannot rename key to same name:', from); + errors.push(...res.errors); + if (prefs.abortEarly) { + return errors; + } + + errored = true; + break; + } + } + + if (errored) { + continue; + } + + if ((schema.$_terms._inclusions.length || schema.$_terms._requireds.length) && + !isValid) { - Common.assertOptions(options, ['alias', 'ignoreUndefined', 'override', 'multiple']); + if (stripUnknown) { + internals.fastSplice(value, i); + --i; + --il; + continue; + } - const obj = this.clone(); + errors.push(error('array.includes', { pos: i, value: item }, state.localize(path))); + if (prefs.abortEarly) { + return errors; + } + } + } - obj.$_terms.renames = obj.$_terms.renames || []; - for (const rename of obj.$_terms.renames) { - Assert(rename.from !== from, 'Cannot rename the same key multiple times'); + if (requireds.length) { + internals.fillMissedErrors(schema, errors, requireds, value, state, prefs); } - if (to instanceof Template) { - obj.$_mutateRegister(to); + if (ordereds.length) { + internals.fillOrderedErrors(schema, errors, ordereds, value, state, prefs); + + if (!errors.length) { + internals.fillDefault(ordereds, value, state, prefs); + } } - obj.$_terms.renames.push({ - from, - to, - options: ApplyToDefaults(internals.renameDefaults, options) - }); + return errors.length ? errors : value; + }, - return obj; - } + priority: true, + manifest: false }, - schema: { - method(type = 'any') { + length: { + method(limit) { - return this.$_addRule({ name: 'schema', args: { type } }); + return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); }, - validate(value, helpers, { type }) { - - if (Common.isSchema(value) && - (type === 'any' || value.type === type)) { + validate(value, helpers, { limit }, { name, operator, args }) { + if (Common.compare(value.length, limit, operator)) { return value; } - return helpers.error('object.schema', { type }); - } - }, - - unknown: { - method(allow) { - - return this.$_setFlag('unknown', allow !== false); - } + return helpers.error('array.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.limit, + message: 'must be a positive integer' + } + ] }, - with: { - method(key, peers, options = {}) { + max: { + method(limit) { - return internals.dependency(this, 'with', key, peers, options); + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); } }, - without: { - method(key, peers, options = {}) { + min: { + method(limit) { - return internals.dependency(this, 'without', key, peers, options); + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); } }, - xor: { - method(...peers /*, [options] */) { + ordered: { + method(...schemas) { - Common.verifyFlat(peers, 'xor'); + Common.verifyFlat(schemas, 'ordered'); - return internals.dependency(this, 'xor', null, peers); - } - } - }, + const obj = this.$_addRule('items'); - overrides: { + for (let i = 0; i < schemas.length; ++i) { + const type = Common.tryWithPath(() => this.$_compile(schemas[i]), i, { append: true }); + internals.validateSingle(type, obj); - default(value, options) { + obj.$_mutateRegister(type); + obj.$_terms.ordered.push(type); + } - if (value === undefined) { - value = Common.symbols.deepDefault; + return obj.$_mutateRebuild(); } + }, - return this.$_parent('default', value, options); - } - }, + single: { + method(enabled) { - rebuild(schema) { + const value = enabled === undefined ? true : !!enabled; + Assert(!value || !this._flags._arrayItems, 'Cannot specify single rule when array has array items'); - if (schema.$_terms.keys) { - const topo = new Topo.Sorter(); - for (const child of schema.$_terms.keys) { - Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key }), child.key); + return this.$_setFlag('single', value); } + }, - schema.$_terms.keys = new internals.Keys(...topo.nodes); - } - }, - - manifest: { + sort: { + method(options = {}) { - build(obj, desc) { + Common.assertOptions(options, ['by', 'order']); - if (desc.keys) { - obj = obj.keys(desc.keys); - } + const settings = { + order: options.order || 'ascending' + }; - if (desc.dependencies) { - for (const { rel, key = null, peers, options } of desc.dependencies) { - obj = internals.dependency(obj, rel, key, peers, options); + if (options.by) { + settings.by = Compile.ref(options.by, { ancestor: 0 }); + Assert(!settings.by.ancestor, 'Cannot sort by ancestor'); } - } - if (desc.patterns) { - for (const { regex, schema, rule, fallthrough, matches } of desc.patterns) { - obj = obj.pattern(regex || schema, rule, { fallthrough, matches }); - } - } + return this.$_addRule({ name: 'sort', args: { options: settings } }); + }, + validate(value, { error, state, prefs, schema }, { options }) { - if (desc.renames) { - for (const { from, to, options } of desc.renames) { - obj = obj.rename(from, to, options); + const { value: sorted, errors } = internals.sort(schema, value, options, state, prefs); + if (errors) { + return errors; } - } - return obj; - } - }, + for (let i = 0; i < value.length; ++i) { + if (value[i] !== sorted[i]) { + return error('array.sort', { order: options.order, by: options.by ? options.by.key : 'value' }); + } + } - messages: { - 'object.and': '{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}', - 'object.assert': '{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}', - 'object.base': '{{#label}} must be of type {{#type}}', - 'object.instance': '{{#label}} must be an instance of {{:#type}}', - 'object.length': '{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}', - 'object.max': '{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}', - 'object.min': '{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}', - 'object.missing': '{{#label}} must contain at least one of {{#peersWithLabels}}', - 'object.nand': '{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}', - 'object.oxor': '{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}', - 'object.pattern.match': '{{#label}} keys failed to match pattern requirements', - 'object.refType': '{{#label}} must be a Joi reference', - 'object.regex': '{{#label}} must be a RegExp object', - 'object.rename.multiple': '{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}', - 'object.rename.override': '{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists', - 'object.schema': '{{#label}} must be a Joi schema of {{#type}} type', - 'object.unknown': '{{#label}} is not allowed', - 'object.with': '{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}', - 'object.without': '{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}', - 'object.xor': '{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}' - } -}); + return value; + }, + convert: true + }, + sparse: { + method(enabled) { -// Helpers + const value = enabled === undefined ? true : !!enabled; -internals.clone = function (value, prefs) { + if (this._flags.sparse === value) { + return this; + } - // Object + const obj = value ? this.clone() : this.$_addRule('items'); + return obj.$_setFlag('sparse', value, { clone: false }); + } + }, - if (typeof value === 'object') { - if (prefs.nonEnumerables) { - return Clone(value, { shallow: true }); - } + unique: { + method(comparator, options = {}) { - const clone = Object.create(Object.getPrototypeOf(value)); - Object.assign(clone, value); - return clone; - } + Assert(!comparator || typeof comparator === 'function' || typeof comparator === 'string', 'comparator must be a function or a string'); + Common.assertOptions(options, ['ignoreUndefined', 'separator']); - // Function + const rule = { name: 'unique', args: { options, comparator } }; - const clone = function (...args) { + if (comparator) { + if (typeof comparator === 'string') { + const separator = Common.default(options.separator, '.'); + rule.path = separator ? comparator.split(separator) : [comparator]; + } + else { + rule.comparator = comparator; + } + } - return value.apply(this, args); - }; + return this.$_addRule(rule); + }, + validate(value, { state, error, schema }, { comparator: raw, options }, { comparator, path }) { - clone.prototype = Clone(value.prototype); - Object.defineProperty(clone, 'name', { value: value.name, writable: false }); - Object.defineProperty(clone, 'length', { value: value.length, writable: false }); - Object.assign(clone, value); - return clone; -}; + const found = { + string: Object.create(null), + number: Object.create(null), + undefined: Object.create(null), + boolean: Object.create(null), + bigint: Object.create(null), + object: new Map(), + function: new Map(), + custom: new Map() + }; + const compare = comparator || DeepEqual; + const ignoreUndefined = options.ignoreUndefined; -internals.dependency = function (schema, rel, key, peers, options) { + for (let i = 0; i < value.length; ++i) { + const item = path ? Reach(value[i], path) : value[i]; + const records = comparator ? found.custom : found[typeof item]; + Assert(records, 'Failed to find unique map container for type', typeof item); - Assert(key === null || typeof key === 'string', rel, 'key must be a strings'); + if (records instanceof Map) { + const entries = records.entries(); + let current; + while (!(current = entries.next()).done) { + if (compare(current.value[0], item)) { + const localState = state.localize([...state.path, i], [value, ...state.ancestors]); + const context = { + pos: i, + value: value[i], + dupePos: current.value[1], + dupeValue: value[current.value[1]] + }; - // Extract options from peers array + if (path) { + context.path = raw; + } - if (!options) { - options = peers.length > 1 && typeof peers[peers.length - 1] === 'object' ? peers.pop() : {}; - } + return error('array.unique', context, localState); + } + } - Common.assertOptions(options, ['separator', 'isPresent']); + records.set(item, i); + } + else { + if ((!ignoreUndefined || item !== undefined) && + records[item] !== undefined) { - peers = [].concat(peers); + const context = { + pos: i, + value: value[i], + dupePos: records[item], + dupeValue: value[records[item]] + }; - // Cast peer paths + if (path) { + context.path = raw; + } - const separator = Common.default(options.separator, '.'); - const paths = []; - for (const peer of peers) { - Assert(typeof peer === 'string', rel, 'peers must be strings'); - paths.push(Compile.ref(peer, { separator, ancestor: 0, prefix: false })); - } + const localState = state.localize([...state.path, i], [value, ...state.ancestors]); + return error('array.unique', context, localState); + } - // Cast key + records[item] = i; + } + } - if (key !== null) { - key = Compile.ref(key, { separator, ancestor: 0, prefix: false }); - } + return value; + }, + args: ['comparator', 'options'], + multi: true + } + }, - // Add rule + cast: { + set: { + from: Array.isArray, + to(value, helpers) { - const obj = schema.clone(); - obj.$_terms.dependencies = obj.$_terms.dependencies || []; - obj.$_terms.dependencies.push(new internals.Dependency(rel, key, paths, peers, options)); - return obj; -}; + return new Set(value); + } + } + }, + rebuild(schema) { -internals.dependencies = { + schema.$_terms._inclusions = []; + schema.$_terms._exclusions = []; + schema.$_terms._requireds = []; - and(schema, dep, value, state, prefs) { + for (const type of schema.$_terms.items) { + internals.validateSingle(type, schema); - const missing = []; - const present = []; - const count = dep.peers.length; - const isPresent = internals.isPresent(dep.options); - for (const peer of dep.peers) { - if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false })) === false) { - missing.push(peer.key); + if (type._flags.presence === 'required') { + schema.$_terms._requireds.push(type); + } + else if (type._flags.presence === 'forbidden') { + schema.$_terms._exclusions.push(type); } else { - present.push(peer.key); + schema.$_terms._inclusions.push(type); } } - if (missing.length !== count && - present.length !== count) { - - return { - code: 'object.and', - context: { - present, - presentWithLabels: internals.keysToLabels(schema, present), - missing, - missingWithLabels: internals.keysToLabels(schema, missing) - } - }; + for (const type of schema.$_terms.ordered) { + internals.validateSingle(type, schema); } }, - nand(schema, dep, value, state, prefs) { - - const present = []; - const isPresent = internals.isPresent(dep.options); - for (const peer of dep.peers) { - if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { - present.push(peer.key); - } - } + manifest: { - if (present.length !== dep.peers.length) { - return; - } + build(obj, desc) { - const main = dep.paths[0]; - const values = dep.paths.slice(1); - return { - code: 'object.nand', - context: { - main, - mainWithLabel: internals.keysToLabels(schema, main), - peers: values, - peersWithLabels: internals.keysToLabels(schema, values) + if (desc.items) { + obj = obj.items(...desc.items); } - }; - }, - - or(schema, dep, value, state, prefs) { - const isPresent = internals.isPresent(dep.options); - for (const peer of dep.peers) { - if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { - return; + if (desc.ordered) { + obj = obj.ordered(...desc.ordered); } - } - return { - code: 'object.missing', - context: { - peers: dep.paths, - peersWithLabels: internals.keysToLabels(schema, dep.paths) - } - }; + return obj; + } }, - oxor(schema, dep, value, state, prefs) { + messages: { + 'array.base': '{{#label}} must be an array', + 'array.excludes': '{{#label}} contains an excluded value', + 'array.hasKnown': '{{#label}} does not contain at least one required match for type {:#patternLabel}', + 'array.hasUnknown': '{{#label}} does not contain at least one required match', + 'array.includes': '{{#label}} does not match any of the allowed types', + 'array.includesRequiredBoth': '{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)', + 'array.includesRequiredKnowns': '{{#label}} does not contain {{#knownMisses}}', + 'array.includesRequiredUnknowns': '{{#label}} does not contain {{#unknownMisses}} required value(s)', + 'array.length': '{{#label}} must contain {{#limit}} items', + 'array.max': '{{#label}} must contain less than or equal to {{#limit}} items', + 'array.min': '{{#label}} must contain at least {{#limit}} items', + 'array.orderedLength': '{{#label}} must contain at most {{#limit}} items', + 'array.sort': '{{#label}} must be sorted in {#order} order by {{#by}}', + 'array.sort.mismatching': '{{#label}} cannot be sorted due to mismatching types', + 'array.sort.unsupported': '{{#label}} cannot be sorted due to unsupported type {#type}', + 'array.sparse': '{{#label}} must not be a sparse array item', + 'array.unique': '{{#label}} contains a duplicate value' + } +}); - const present = []; - const isPresent = internals.isPresent(dep.options); - for (const peer of dep.peers) { - if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { - present.push(peer.key); - } - } - if (!present.length || - present.length === 1) { +// Helpers - return; +internals.fillMissedErrors = function (schema, errors, requireds, value, state, prefs) { + + const knownMisses = []; + let unknownMisses = 0; + for (const required of requireds) { + const label = required._flags.label; + if (label) { + knownMisses.push(label); } + else { + ++unknownMisses; + } + } - const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; - context.present = present; - context.presentWithLabels = internals.keysToLabels(schema, present); - return { code: 'object.oxor', context }; - }, + if (knownMisses.length) { + if (unknownMisses) { + errors.push(schema.$_createError('array.includesRequiredBoth', value, { knownMisses, unknownMisses }, state, prefs)); + } + else { + errors.push(schema.$_createError('array.includesRequiredKnowns', value, { knownMisses }, state, prefs)); + } + } + else { + errors.push(schema.$_createError('array.includesRequiredUnknowns', value, { unknownMisses }, state, prefs)); + } +}; - with(schema, dep, value, state, prefs) { - const isPresent = internals.isPresent(dep.options); - for (const peer of dep.peers) { - if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false })) === false) { - return { - code: 'object.with', - context: { - main: dep.key.key, - mainWithLabel: internals.keysToLabels(schema, dep.key.key), - peer: peer.key, - peerWithLabel: internals.keysToLabels(schema, peer.key) - } - }; - } - } - }, +internals.fillOrderedErrors = function (schema, errors, ordereds, value, state, prefs) { - without(schema, dep, value, state, prefs) { + const requiredOrdereds = []; - const isPresent = internals.isPresent(dep.options); - for (const peer of dep.peers) { - if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { - return { - code: 'object.without', - context: { - main: dep.key.key, - mainWithLabel: internals.keysToLabels(schema, dep.key.key), - peer: peer.key, - peerWithLabel: internals.keysToLabels(schema, peer.key) - } - }; - } + for (const ordered of ordereds) { + if (ordered._flags.presence === 'required') { + requiredOrdereds.push(ordered); } - }, + } + + if (requiredOrdereds.length) { + internals.fillMissedErrors(schema, errors, requiredOrdereds, value, state, prefs); + } +}; - xor(schema, dep, value, state, prefs) { - const present = []; - const isPresent = internals.isPresent(dep.options); - for (const peer of dep.peers) { - if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { - present.push(peer.key); +internals.fillDefault = function (ordereds, value, state, prefs) { + + const overrides = []; + let trailingUndefined = true; + + for (let i = ordereds.length - 1; i >= 0; --i) { + const ordered = ordereds[i]; + const ancestors = [value, ...state.ancestors]; + const override = ordered.$_validate(undefined, state.localize(state.path, ancestors, ordered), prefs).value; + + if (trailingUndefined) { + if (override === undefined) { + continue; } - } - if (present.length === 1) { - return; + trailingUndefined = false; } - const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; - if (present.length === 0) { - return { code: 'object.missing', context }; - } + overrides.unshift(override); + } - context.present = present; - context.presentWithLabels = internals.keysToLabels(schema, present); - return { code: 'object.xor', context }; + if (overrides.length) { + value.push(...overrides); } }; -internals.keysToLabels = function (schema, keys) { +internals.fastSplice = function (arr, i) { - if (Array.isArray(keys)) { - return keys.map((key) => schema.$_mapLabels(key)); + let pos = i; + while (pos < arr.length) { + arr[pos++] = arr[pos]; } - return schema.$_mapLabels(keys); + --arr.length; }; -internals.isPresent = function (options) { +internals.validateSingle = function (type, obj) { - return typeof options.isPresent === 'function' ? options.isPresent : (resolved) => resolved !== undefined; + if (type.type === 'array' || + type._flags._arrayItems) { + + Assert(!obj._flags.single, 'Cannot specify array item with single rule enabled'); + obj.$_setFlag('_arrayItems', true, { clone: false }); + } }; -internals.rename = function (schema, value, state, prefs, errors) { +internals.sort = function (schema, value, settings, state, prefs) { - const renamed = {}; - for (const rename of schema.$_terms.renames) { - const matches = []; - const pattern = typeof rename.from !== 'string'; + const order = settings.order === 'ascending' ? 1 : -1; + const aFirst = -1 * order; + const bFirst = order; - if (!pattern) { - if (Object.prototype.hasOwnProperty.call(value, rename.from) && - (value[rename.from] !== undefined || !rename.options.ignoreUndefined)) { + const sort = (a, b) => { - matches.push(rename); - } + let compare = internals.compare(a, b, aFirst, bFirst); + if (compare !== null) { + return compare; } - else { - for (const from in value) { - if (value[from] === undefined && - rename.options.ignoreUndefined) { - - continue; - } - if (from === rename.to) { - continue; - } + if (settings.by) { + a = settings.by.resolve(a, state, prefs); + b = settings.by.resolve(b, state, prefs); + } - const match = rename.from.exec(from); - if (!match) { - continue; - } + compare = internals.compare(a, b, aFirst, bFirst); + if (compare !== null) { + return compare; + } - matches.push({ from, to: rename.to, match }); - } + const type = typeof a; + if (type !== typeof b) { + throw schema.$_createError('array.sort.mismatching', value, null, state, prefs); } - for (const match of matches) { - const from = match.from; - let to = match.to; - if (to instanceof Template) { - to = to.render(value, state, prefs, match.match); - } + if (type !== 'number' && + type !== 'string') { - if (from === to) { - continue; - } + throw schema.$_createError('array.sort.unsupported', value, { type }, state, prefs); + } - if (!rename.options.multiple && - renamed[to]) { + if (type === 'number') { + return (a - b) * order; + } - errors.push(schema.$_createError('object.rename.multiple', value, { from, to, pattern }, state, prefs)); - if (prefs.abortEarly) { - return false; - } - } + return a < b ? aFirst : bFirst; + }; - if (Object.prototype.hasOwnProperty.call(value, to) && - !rename.options.override && - !renamed[to]) { + try { + return { value: value.slice().sort(sort) }; + } + catch (err) { + return { errors: err }; + } +}; - errors.push(schema.$_createError('object.rename.override', value, { from, to, pattern }, state, prefs)); - if (prefs.abortEarly) { - return false; - } - } - if (value[from] === undefined) { - delete value[to]; - } - else { - value[to] = value[from]; - } +internals.compare = function (a, b, aFirst, bFirst) { - renamed[to] = true; + if (a === b) { + return 0; + } - if (!rename.options.alias) { - delete value[from]; - } - } + if (a === undefined) { + return 1; // Always last regardless of sort order } - return true; -}; + if (b === undefined) { + return -1; // Always last regardless of sort order + } + if (a === null) { + return bFirst; + } -internals.unknown = function (schema, value, unprocessed, errors, state, prefs) { + if (b === null) { + return aFirst; + } - if (schema.$_terms.patterns) { - let hasMatches = false; - const matches = schema.$_terms.patterns.map((pattern) => { + return null; +}; - if (pattern.matches) { - hasMatches = true; - return []; - } - }); - const ancestors = [value, ...state.ancestors]; +/***/ }), - for (const key of unprocessed) { - const item = value[key]; - const path = [...state.path, key]; +/***/ 34288: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (let i = 0; i < schema.$_terms.patterns.length; ++i) { - const pattern = schema.$_terms.patterns[i]; - if (pattern.regex) { - const match = pattern.regex.test(key); - state.mainstay.tracer.debug(state, 'rule', `pattern.${i}`, match ? 'pass' : 'error'); - if (!match) { - continue; - } - } - else { - if (!pattern.schema.$_match(key, state.nest(pattern.schema, `pattern.${i}`), prefs)) { - continue; - } - } +"use strict"; - unprocessed.delete(key); - const localState = state.localize(path, ancestors, { schema: pattern.rule, key }); - const result = pattern.rule.$_validate(item, localState, prefs); - if (result.errors) { - if (prefs.abortEarly) { - return { value, errors: result.errors }; - } +const Assert = __nccwpck_require__(32718); - errors.push(...result.errors); - } +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); - if (pattern.matches) { - matches[i].push(key); - } - value[key] = result.value; - if (!pattern.fallthrough) { - break; - } - } - } +const internals = {}; - // Validate pattern matches rules - if (hasMatches) { - for (let i = 0; i < matches.length; ++i) { - const match = matches[i]; - if (!match) { - continue; - } +module.exports = Any.extend({ - const stpm = schema.$_terms.patterns[i].matches; - const localState = state.localize(state.path, ancestors, stpm); - const result = stpm.$_validate(match, localState, prefs); - if (result.errors) { - const details = Errors.details(result.errors, { override: false }); - details.matches = match; - const report = schema.$_createError('object.pattern.match', value, details, state, prefs); - if (prefs.abortEarly) { - return { value, errors: report }; - } + type: 'binary', - errors.push(report); + coerce: { + from: ['string', 'object'], + method(value, { schema }) { + + if (typeof value === 'string' || (value !== null && value.type === 'Buffer')) { + try { + return { value: Buffer.from(value, schema._flags.encoding) }; } + catch (ignoreErr) { } } } - } - - if (!unprocessed.size || - !schema.$_terms.keys && !schema.$_terms.patterns) { // If no keys or patterns specified, unknown keys allowed - - return; - } - - if (prefs.stripUnknown && !schema._flags.unknown || - prefs.skipFunctions) { + }, - const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false; + validate(value, { error }) { - for (const key of unprocessed) { - if (stripUnknown) { - delete value[key]; - unprocessed.delete(key); - } - else if (typeof value[key] === 'function') { - unprocessed.delete(key); - } + if (!Buffer.isBuffer(value)) { + return { value, errors: error('binary.base') }; } - } + }, - const forbidUnknown = !Common.default(schema._flags.unknown, prefs.allowUnknown); - if (forbidUnknown) { - for (const unprocessedKey of unprocessed) { - const localState = state.localize([...state.path, unprocessedKey], []); - const report = schema.$_createError('object.unknown', value[unprocessedKey], { child: unprocessedKey }, localState, prefs, { flags: false }); - if (prefs.abortEarly) { - return { value, errors: report }; - } + rules: { + encoding: { + method(encoding) { - errors.push(report); - } - } -}; + Assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); + return this.$_setFlag('encoding', encoding); + } + }, -internals.Dependency = class { + length: { + method(limit) { - constructor(rel, key, peers, paths, options) { + return this.$_addRule({ name: 'length', method: 'length', args: { limit }, operator: '=' }); + }, + validate(value, helpers, { limit }, { name, operator, args }) { - this.rel = rel; - this.key = key; - this.peers = peers; - this.paths = paths; - this.options = options; - } + if (Common.compare(value.length, limit, operator)) { + return value; + } - describe() { + return helpers.error('binary.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.limit, + message: 'must be a positive integer' + } + ] + }, - const desc = { - rel: this.rel, - peers: this.paths - }; + max: { + method(limit) { - if (this.key !== null) { - desc.key = this.key.key; - } + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); + } + }, - if (this.peers[0].separator !== '.') { - desc.options = { ...desc.options, separator: this.peers[0].separator }; - } + min: { + method(limit) { - if (this.options.isPresent) { - desc.options = { ...desc.options, isPresent: this.options.isPresent }; + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); + } } + }, - return desc; - } -}; - - -internals.Keys = class extends Array { - - concat(source) { - - const result = this.slice(); - - const keys = new Map(); - for (let i = 0; i < result.length; ++i) { - keys.set(result[i].key, i); - } + cast: { + string: { + from: (value) => Buffer.isBuffer(value), + to(value, helpers) { - for (const item of source) { - const key = item.key; - const pos = keys.get(key); - if (pos !== undefined) { - result[pos] = { key, schema: result[pos].schema.concat(item.schema) }; - } - else { - result.push(item); + return value.toString(); } } + }, - return result; + messages: { + 'binary.base': '{{#label}} must be a buffer or a string', + 'binary.length': '{{#label}} must be {{#limit}} bytes', + 'binary.max': '{{#label}} must be less than or equal to {{#limit}} bytes', + 'binary.min': '{{#label}} must be at least {{#limit}} bytes' } -}; +}); /***/ }), -/***/ 69869: +/***/ 47489: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -28694,173 +28910,155 @@ const Assert = __nccwpck_require__(32718); const Any = __nccwpck_require__(9512); const Common = __nccwpck_require__(72448); -const Compile = __nccwpck_require__(3038); -const Errors = __nccwpck_require__(69490); +const Values = __nccwpck_require__(71944); const internals = {}; -module.exports = Any.extend({ - - type: 'link', - - properties: { - schemaChain: true - }, - - terms: { - - link: { init: null, manifest: 'single', register: false } - }, - - args(schema, ref) { +internals.isBool = function (value) { - return schema.ref(ref); - }, + return typeof value === 'boolean'; +}; - validate(value, { schema, state, prefs }) { - Assert(schema.$_terms.link, 'Uninitialized link schema'); +module.exports = Any.extend({ - const linked = internals.generate(schema, value, state, prefs); - const ref = schema.$_terms.link[0].ref; - return linked.$_validate(value, state.nest(linked, `link:${ref.display}:${linked.type}`), prefs); - }, + type: 'boolean', - generate(schema, value, state, prefs) { + flags: { - return internals.generate(schema, value, state, prefs); + sensitive: { default: false } }, - rules: { - - ref: { - method(ref) { - - Assert(!this.$_terms.link, 'Cannot reinitialize schema'); - - ref = Compile.ref(ref); - - Assert(ref.type === 'value' || ref.type === 'local', 'Invalid reference type:', ref.type); - Assert(ref.type === 'local' || ref.ancestor === 'root' || ref.ancestor > 0, 'Link cannot reference itself'); + terms: { - const obj = this.clone(); - obj.$_terms.link = [{ ref }]; - return obj; - } + falsy: { + init: null, + manifest: 'values' }, - relative: { - method(enabled = true) { - - return this.$_setFlag('relative', enabled); - } + truthy: { + init: null, + manifest: 'values' } }, - overrides: { + coerce(value, { schema }) { - concat(source) { + if (typeof value === 'boolean') { + return; + } - Assert(this.$_terms.link, 'Uninitialized link schema'); - Assert(Common.isSchema(source), 'Invalid schema object'); - Assert(source.type !== 'link', 'Cannot merge type link with another link'); + if (typeof value === 'string') { + const normalized = schema._flags.sensitive ? value : value.toLowerCase(); + value = normalized === 'true' ? true : (normalized === 'false' ? false : value); + } - const obj = this.clone(); + if (typeof value !== 'boolean') { + value = schema.$_terms.truthy && schema.$_terms.truthy.has(value, null, null, !schema._flags.sensitive) || + (schema.$_terms.falsy && schema.$_terms.falsy.has(value, null, null, !schema._flags.sensitive) ? false : value); + } - if (!obj.$_terms.whens) { - obj.$_terms.whens = []; - } + return { value }; + }, - obj.$_terms.whens.push({ concat: source }); - return obj.$_mutateRebuild(); + validate(value, { error }) { + + if (typeof value !== 'boolean') { + return { value, errors: error('boolean.base') }; } }, - manifest: { + rules: { + truthy: { + method(...values) { - build(obj, desc) { + Common.verifyFlat(values, 'truthy'); - Assert(desc.link, 'Invalid link description missing link'); - return obj.ref(desc.link); - } - } -}); + const obj = this.clone(); + obj.$_terms.truthy = obj.$_terms.truthy || new Values(); + for (let i = 0; i < values.length; ++i) { + const value = values[i]; -// Helpers + Assert(value !== undefined, 'Cannot call truthy with undefined'); + obj.$_terms.truthy.add(value); + } -internals.generate = function (schema, value, state, prefs) { + return obj; + } + }, - let linked = state.mainstay.links.get(schema); - if (linked) { - return linked._generate(value, state, prefs).schema; - } + falsy: { + method(...values) { - const ref = schema.$_terms.link[0].ref; - const { perspective, path } = internals.perspective(ref, state); - internals.assert(perspective, 'which is outside of schema boundaries', ref, schema, state, prefs); + Common.verifyFlat(values, 'falsy'); - try { - linked = path.length ? perspective.$_reach(path) : perspective; - } - catch (ignoreErr) { - internals.assert(false, 'to non-existing schema', ref, schema, state, prefs); - } + const obj = this.clone(); + obj.$_terms.falsy = obj.$_terms.falsy || new Values(); - internals.assert(linked.type !== 'link', 'which is another link', ref, schema, state, prefs); + for (let i = 0; i < values.length; ++i) { + const value = values[i]; - if (!schema._flags.relative) { - state.mainstay.links.set(schema, linked); - } + Assert(value !== undefined, 'Cannot call falsy with undefined'); + obj.$_terms.falsy.add(value); + } - return linked._generate(value, state, prefs).schema; -}; + return obj; + } + }, + sensitive: { + method(enabled = true) { -internals.perspective = function (ref, state) { + return this.$_setFlag('sensitive', enabled); + } + } + }, - if (ref.type === 'local') { - for (const { schema, key } of state.schemas) { // From parent to root - const id = schema._flags.id || key; - if (id === ref.path[0]) { - return { perspective: schema, path: ref.path.slice(1) }; + cast: { + number: { + from: internals.isBool, + to(value, helpers) { + + return value ? 1 : 0; } + }, + string: { + from: internals.isBool, + to(value, helpers) { - if (schema.$_terms.shared) { - for (const shared of schema.$_terms.shared) { - if (shared._flags.id === ref.path[0]) { - return { perspective: shared, path: ref.path.slice(1) }; - } - } + return value ? 'true' : 'false'; } } + }, - return { perspective: null, path: null }; - } + manifest: { - if (ref.ancestor === 'root') { - return { perspective: state.schemas[state.schemas.length - 1].schema, path: ref.path }; - } + build(obj, desc) { - return { perspective: state.schemas[ref.ancestor] && state.schemas[ref.ancestor].schema, path: ref.path }; -}; + if (desc.truthy) { + obj = obj.truthy(...desc.truthy); + } + if (desc.falsy) { + obj = obj.falsy(...desc.falsy); + } -internals.assert = function (condition, message, ref, schema, state, prefs) { + return obj; + } + }, - if (condition) { // Manual check to avoid generating error message on success - return; + messages: { + 'boolean.base': '{{#label}} must be a boolean' } - - Assert(false, `"${Errors.label(schema._flags, state, prefs)}" contains link reference "${ref.display}" ${message}`); -}; +}); /***/ }), -/***/ 15855: +/***/ 6624: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -28870,857 +29068,623 @@ const Assert = __nccwpck_require__(32718); const Any = __nccwpck_require__(9512); const Common = __nccwpck_require__(72448); +const Template = __nccwpck_require__(51396); -const internals = { - numberRx: /^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i, - precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/, - exponentialPartRegex: /[eE][+-]?\d+$/, - leadingSignAndZerosRegex: /^[+-]?(0*)?/, - dotRegex: /\./, - trailingZerosRegex: /0+$/ -}; - - -module.exports = Any.extend({ - - type: 'number', - - flags: { +const internals = {}; - unsafe: { default: false } - }, - coerce: { - from: 'string', - method(value, { schema, error }) { +internals.isDate = function (value) { - const matches = value.match(internals.numberRx); - if (!matches) { - return; - } + return value instanceof Date; +}; - value = value.trim(); - const result = { value: parseFloat(value) }; - if (result.value === 0) { - result.value = 0; // -0 - } +module.exports = Any.extend({ - if (!schema._flags.unsafe) { - if (value.match(/e/i)) { - if (internals.extractSignificantDigits(value) !== internals.extractSignificantDigits(String(result.value))) { - result.errors = error('number.unsafe'); - return result; - } - } - else { - const string = result.value.toString(); - if (string.match(/e/i)) { - return result; - } + type: 'date', - if (string !== internals.normalizeDecimal(value)) { - result.errors = error('number.unsafe'); - return result; - } - } - } + coerce: { + from: ['number', 'string'], + method(value, { schema }) { - return result; + return { value: internals.parse(value, schema._flags.format) || value }; } }, validate(value, { schema, error, prefs }) { - if (value === Infinity || - value === -Infinity) { - - return { value, errors: error('number.infinity') }; - } - - if (!Common.isNumber(value)) { - return { value, errors: error('number.base') }; - } - - const result = { value }; + if (value instanceof Date && + !isNaN(value.getTime())) { - if (prefs.convert) { - const rule = schema.$_getRule('precision'); - if (rule) { - const precision = Math.pow(10, rule.args.limit); // This is conceptually equivalent to using toFixed but it should be much faster - result.value = Math.round(result.value * precision) / precision; - } + return; } - if (result.value === 0) { - result.value = 0; // -0 - } + const format = schema._flags.format; - if (!schema._flags.unsafe && - (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)) { + if (!prefs.convert || + !format || + typeof value !== 'string') { - result.errors = error('number.unsafe'); + return { value, errors: error('date.base') }; } - return result; + return { value, errors: error('date.format', { format }) }; }, rules: { compare: { method: false, - validate(value, helpers, { limit }, { name, operator, args }) { + validate(value, helpers, { date }, { name, operator, args }) { - if (Common.compare(value, limit, operator)) { + const to = date === 'now' ? Date.now() : date.getTime(); + if (Common.compare(value.getTime(), to, operator)) { return value; } - return helpers.error('number.' + name, { limit: args.limit, value }); + return helpers.error('date.' + name, { limit: args.date, value }); }, args: [ { - name: 'limit', + name: 'date', ref: true, - assert: Common.isNumber, - message: 'must be a number' - } - ] - }, - - greater: { - method(limit) { - - return this.$_addRule({ name: 'greater', method: 'compare', args: { limit }, operator: '>' }); - } - }, - - integer: { - method() { - - return this.$_addRule('integer'); - }, - validate(value, helpers) { + normalize: (date) => { - if (Math.trunc(value) - value === 0) { - return value; + return date === 'now' ? date : internals.parse(date); + }, + assert: (date) => date !== null, + message: 'must have a valid date format' } - - return helpers.error('number.integer'); - } + ] }, - less: { - method(limit) { - - return this.$_addRule({ name: 'less', method: 'compare', args: { limit }, operator: '<' }); - } - }, + format: { + method(format) { - max: { - method(limit) { + Assert(['iso', 'javascript', 'unix'].includes(format), 'Unknown date format', format); - return this.$_addRule({ name: 'max', method: 'compare', args: { limit }, operator: '<=' }); + return this.$_setFlag('format', format); } }, - min: { - method(limit) { + greater: { + method(date) { - return this.$_addRule({ name: 'min', method: 'compare', args: { limit }, operator: '>=' }); + return this.$_addRule({ name: 'greater', method: 'compare', args: { date }, operator: '>' }); } }, - multiple: { - method(base) { - - return this.$_addRule({ name: 'multiple', args: { base } }); - }, - validate(value, helpers, { base }, options) { - - if (value * (1 / base) % 1 === 0) { - return value; - } - - return helpers.error('number.multiple', { multiple: options.args.base, value }); - }, - args: [ - { - name: 'base', - ref: true, - assert: (value) => typeof value === 'number' && isFinite(value) && value > 0, - message: 'must be a positive number' - } - ], - multi: true - }, - - negative: { + iso: { method() { - return this.sign('negative'); + return this.format('iso'); } }, - port: { - method() { - - return this.$_addRule('port'); - }, - validate(value, helpers) { - - if (Number.isSafeInteger(value) && - value >= 0 && - value <= 65535) { - - return value; - } + less: { + method(date) { - return helpers.error('number.port'); + return this.$_addRule({ name: 'less', method: 'compare', args: { date }, operator: '<' }); } }, - positive: { - method() { + max: { + method(date) { - return this.sign('positive'); + return this.$_addRule({ name: 'max', method: 'compare', args: { date }, operator: '<=' }); } }, - precision: { - method(limit) { - - Assert(Number.isSafeInteger(limit), 'limit must be an integer'); - - return this.$_addRule({ name: 'precision', args: { limit } }); - }, - validate(value, helpers, { limit }) { - - const places = value.toString().match(internals.precisionRx); - const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0); - if (decimals <= limit) { - return value; - } - - return helpers.error('number.precision', { limit, value }); - }, - convert: true - }, - - sign: { - method(sign) { - - Assert(['negative', 'positive'].includes(sign), 'Invalid sign', sign); - - return this.$_addRule({ name: 'sign', args: { sign } }); - }, - validate(value, helpers, { sign }) { - - if (sign === 'negative' && value < 0 || - sign === 'positive' && value > 0) { - - return value; - } + min: { + method(date) { - return helpers.error(`number.${sign}`); + return this.$_addRule({ name: 'min', method: 'compare', args: { date }, operator: '>=' }); } }, - unsafe: { - method(enabled = true) { + timestamp: { + method(type = 'javascript') { - Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); + Assert(['javascript', 'unix'].includes(type), '"type" must be one of "javascript, unix"'); - return this.$_setFlag('unsafe', enabled); + return this.format(type); } } }, cast: { - string: { - from: (value) => typeof value === 'number', + number: { + from: internals.isDate, to(value, helpers) { - return value.toString(); + return value.getTime(); + } + }, + string: { + from: internals.isDate, + to(value, { prefs }) { + + return Template.date(value, prefs); } } }, messages: { - 'number.base': '{{#label}} must be a number', - 'number.greater': '{{#label}} must be greater than {{#limit}}', - 'number.infinity': '{{#label}} cannot be infinity', - 'number.integer': '{{#label}} must be an integer', - 'number.less': '{{#label}} must be less than {{#limit}}', - 'number.max': '{{#label}} must be less than or equal to {{#limit}}', - 'number.min': '{{#label}} must be greater than or equal to {{#limit}}', - 'number.multiple': '{{#label}} must be a multiple of {{#multiple}}', - 'number.negative': '{{#label}} must be a negative number', - 'number.port': '{{#label}} must be a valid port', - 'number.positive': '{{#label}} must be a positive number', - 'number.precision': '{{#label}} must have no more than {{#limit}} decimal places', - 'number.unsafe': '{{#label}} must be a safe number' + 'date.base': '{{#label}} must be a valid date', + 'date.format': '{{#label}} must be in {msg("date.format." + #format) || #format} format', + 'date.greater': '{{#label}} must be greater than {{:#limit}}', + 'date.less': '{{#label}} must be less than {{:#limit}}', + 'date.max': '{{#label}} must be less than or equal to {{:#limit}}', + 'date.min': '{{#label}} must be greater than or equal to {{:#limit}}', + + // Messages used in date.format + + 'date.format.iso': 'ISO 8601 date', + 'date.format.javascript': 'timestamp or number of milliseconds', + 'date.format.unix': 'timestamp or number of seconds' } }); // Helpers -internals.extractSignificantDigits = function (value) { - - return value - .replace(internals.exponentialPartRegex, '') - .replace(internals.dotRegex, '') - .replace(internals.trailingZerosRegex, '') - .replace(internals.leadingSignAndZerosRegex, ''); -}; - - -internals.normalizeDecimal = function (str) { +internals.parse = function (value, format) { - str = str - // Remove leading plus signs - .replace(/^\+/, '') - // Remove trailing zeros if there is a decimal point and unecessary decimal points - .replace(/\.0*$/, '') - // Add a integer 0 if the numbers starts with a decimal point - .replace(/^(-?)\.([^\.]*)$/, '$10.$2') - // Remove leading zeros - .replace(/^(-?)0+([0-9])/, '$1$2'); + if (value instanceof Date) { + return value; + } - if (str.includes('.') && - str.endsWith('0')) { + if (typeof value !== 'string' && + (isNaN(value) || !isFinite(value))) { - str = str.replace(/0+$/, ''); + return null; } - if (str === '-0') { - return '0'; + if (/^\s*$/.test(value)) { + return null; } - return str; -}; - - -/***/ }), - -/***/ 46878: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Keys = __nccwpck_require__(79130); - - -const internals = {}; - - -module.exports = Keys.extend({ - - type: 'object', - - cast: { - map: { - from: (value) => value && typeof value === 'object', - to(value, helpers) { + // ISO - return new Map(Object.entries(value)); - } + if (format === 'iso') { + if (!Common.isIsoDate(value)) { + return null; } - } -}); - -/***/ }), + return internals.date(value.toString()); + } -/***/ 72260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Normalize number string -"use strict"; + const original = value; + if (typeof value === 'string' && + /^[+-]?\d+(\.\d+)?$/.test(value)) { + value = parseFloat(value); + } -const Assert = __nccwpck_require__(32718); -const Domain = __nccwpck_require__(97425); -const Email = __nccwpck_require__(3283); -const Ip = __nccwpck_require__(82337); -const EscapeRegex = __nccwpck_require__(91965); -const Tlds = __nccwpck_require__(53092); -const Uri = __nccwpck_require__(74983); + // Timestamp -const Any = __nccwpck_require__(9512); -const Common = __nccwpck_require__(72448); + if (format) { + if (format === 'javascript') { + return internals.date(1 * value); // Casting to number + } + if (format === 'unix') { + return internals.date(1000 * value); + } -const internals = { - tlds: Tlds instanceof Set ? { tlds: { allow: Tlds, deny: null } } : false, // $lab:coverage:ignore$ - base64Regex: { - // paddingRequired - true: { - // urlSafe - true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}==|[\w\-]{3}=)?$/, - false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ - }, - false: { - true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}(==)?|[\w\-]{3}=?)?$/, - false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/ + if (typeof original === 'string') { + return null; } - }, - dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/, - hexRegex: /^[a-f0-9]+$/i, - ipRegex: Ip.regex({ cidr: 'forbidden' }).regex, - isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/, + } - guidBrackets: { - '{': '}', '[': ']', '(': ')', '': '' - }, - guidVersions: { - uuidv1: '1', - uuidv2: '2', - uuidv3: '3', - uuidv4: '4', - uuidv5: '5', - uuidv6: '6', - uuidv7: '7', - uuidv8: '8' - }, - guidSeparators: new Set([undefined, true, false, '-', ':']), + // Plain - normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD'] + return internals.date(value); }; -module.exports = Any.extend({ - - type: 'string', - - flags: { - - insensitive: { default: false }, - truncate: { default: false } - }, - - terms: { - - replacements: { init: null } - }, - - coerce: { - from: 'string', - method(value, { schema, state, prefs }) { - - const normalize = schema.$_getRule('normalize'); - if (normalize) { - value = value.normalize(normalize.args.form); - } +internals.date = function (value) { - const casing = schema.$_getRule('case'); - if (casing) { - value = casing.args.direction === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase(); - } + const date = new Date(value); + if (!isNaN(date.getTime())) { + return date; + } - const trim = schema.$_getRule('trim'); - if (trim && - trim.args.enabled) { + return null; +}; - value = value.trim(); - } - if (schema.$_terms.replacements) { - for (const replacement of schema.$_terms.replacements) { - value = value.replace(replacement.pattern, replacement.replacement); - } - } +/***/ }), - const hex = schema.$_getRule('hex'); - if (hex && - hex.args.options.byteAligned && - value.length % 2 !== 0) { +/***/ 62269: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - value = `0${value}`; - } +"use strict"; - if (schema.$_getRule('isoDate')) { - const iso = internals.isoDate(value); - if (iso) { - value = iso; - } - } - if (schema._flags.truncate) { - const rule = schema.$_getRule('max'); - if (rule) { - let limit = rule.args.limit; - if (Common.isResolvable(limit)) { - limit = limit.resolve(value, state, prefs); - if (!Common.limit(limit)) { - return { value, errors: schema.$_createError('any.ref', limit, { ref: rule.args.limit, arg: 'limit', reason: 'must be a positive integer' }, state, prefs) }; - } - } +const Assert = __nccwpck_require__(32718); - value = value.slice(0, limit); - } - } +const Keys = __nccwpck_require__(79130); - return { value }; - } - }, - validate(value, { schema, error }) { +const internals = {}; - if (typeof value !== 'string') { - return { value, errors: error('string.base') }; - } - if (value === '') { - const min = schema.$_getRule('min'); - if (min && - min.args.limit === 0) { +module.exports = Keys.extend({ - return; - } + type: 'function', - return { value, errors: error('string.empty') }; - } + properties: { + typeof: 'function' }, rules: { + arity: { + method(n) { - alphanum: { + Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); + + return this.$_addRule({ name: 'arity', args: { n } }); + }, + validate(value, helpers, { n }) { + + if (value.length === n) { + return value; + } + + return helpers.error('function.arity', { n }); + } + }, + + class: { method() { - return this.$_addRule('alphanum'); + return this.$_addRule('class'); }, validate(value, helpers) { - if (/^[a-zA-Z0-9]+$/.test(value)) { + if ((/^\s*class\s/).test(value.toString())) { return value; } - return helpers.error('string.alphanum'); + return helpers.error('function.class', { value }); } }, - base64: { - method(options = {}) { - - Common.assertOptions(options, ['paddingRequired', 'urlSafe']); + minArity: { + method(n) { - options = { urlSafe: false, paddingRequired: true, ...options }; - Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); - Assert(typeof options.urlSafe === 'boolean', 'urlSafe must be boolean'); + Assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer'); - return this.$_addRule({ name: 'base64', args: { options } }); + return this.$_addRule({ name: 'minArity', args: { n } }); }, - validate(value, helpers, { options }) { + validate(value, helpers, { n }) { - const regex = internals.base64Regex[options.paddingRequired][options.urlSafe]; - if (regex.test(value)) { + if (value.length >= n) { return value; } - return helpers.error('string.base64'); + return helpers.error('function.minArity', { n }); } }, - case: { - method(direction) { + maxArity: { + method(n) { - Assert(['lower', 'upper'].includes(direction), 'Invalid case:', direction); + Assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); - return this.$_addRule({ name: 'case', args: { direction } }); + return this.$_addRule({ name: 'maxArity', args: { n } }); }, - validate(value, helpers, { direction }) { - - if (direction === 'lower' && value === value.toLocaleLowerCase() || - direction === 'upper' && value === value.toLocaleUpperCase()) { + validate(value, helpers, { n }) { + if (value.length <= n) { return value; } - return helpers.error(`string.${direction}case`); - }, - convert: true - }, + return helpers.error('function.maxArity', { n }); + } + } + }, - creditCard: { - method() { + messages: { + 'function.arity': '{{#label}} must have an arity of {{#n}}', + 'function.class': '{{#label}} must be a class', + 'function.maxArity': '{{#label}} must have an arity lesser or equal to {{#n}}', + 'function.minArity': '{{#label}} must have an arity greater or equal to {{#n}}' + } +}); - return this.$_addRule('creditCard'); - }, - validate(value, helpers) { - let i = value.length; - let sum = 0; - let mul = 1; +/***/ }), - while (i--) { - const char = value.charAt(i) * mul; - sum = sum + (char - (char > 9) * 9); - mul = mul ^ 3; - } +/***/ 79130: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (sum > 0 && - sum % 10 === 0) { +"use strict"; - return value; - } - return helpers.error('string.creditCard'); - } - }, +const ApplyToDefaults = __nccwpck_require__(85545); +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Topo = __nccwpck_require__(88392); - dataUri: { - method(options = {}) { +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); +const Ref = __nccwpck_require__(73838); +const Template = __nccwpck_require__(51396); - Common.assertOptions(options, ['paddingRequired']); - options = { paddingRequired: true, ...options }; - Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); +const internals = { + renameDefaults: { + alias: false, // Keep old value in place + multiple: false, // Allow renaming multiple keys into the same target + override: false // Overrides an existing key + } +}; - return this.$_addRule({ name: 'dataUri', args: { options } }); - }, - validate(value, helpers, { options }) { - const matches = value.match(internals.dataUriRegex); +module.exports = Any.extend({ - if (matches) { - if (!matches[2]) { - return value; - } + type: '_keys', - if (matches[2] !== 'base64') { - return value; - } + properties: { - const base64regex = internals.base64Regex[options.paddingRequired].false; - if (base64regex.test(matches[3])) { - return value; - } - } + typeof: 'object' + }, - return helpers.error('string.dataUri'); - } - }, + flags: { - domain: { - method(options) { + unknown: { default: undefined } + }, - if (options) { - Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); - } + terms: { - const address = internals.addressOptions(options); - return this.$_addRule({ name: 'domain', args: { options }, address }); - }, - validate(value, helpers, args, { address }) { + dependencies: { init: null }, + keys: { init: null, manifest: { mapped: { from: 'schema', to: 'key' } } }, + patterns: { init: null }, + renames: { init: null } + }, - if (Domain.isValid(value, address)) { - return value; - } + args(schema, keys) { - return helpers.error('string.domain'); - } - }, + return schema.keys(keys); + }, - email: { - method(options = {}) { + validate(value, { schema, error, state, prefs }) { - Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'ignoreLength', 'maxDomainSegments', 'minDomainSegments', 'multiple', 'separator', 'tlds']); - Assert(options.multiple === undefined || typeof options.multiple === 'boolean', 'multiple option must be an boolean'); + if (!value || + typeof value !== schema.$_property('typeof') || + Array.isArray(value)) { - const address = internals.addressOptions(options); - const regex = new RegExp(`\\s*[${options.separator ? EscapeRegex(options.separator) : ','}]\\s*`); + return { value, errors: error('object.base', { type: schema.$_property('typeof') }) }; + } - return this.$_addRule({ name: 'email', args: { options }, regex, address }); - }, - validate(value, helpers, { options }, { regex, address }) { + // Skip if there are no other rules to test - const emails = options.multiple ? value.split(regex) : [value]; - const invalids = []; - for (const email of emails) { - if (!Email.isValid(email, address)) { - invalids.push(email); - } - } + if (!schema.$_terms.renames && + !schema.$_terms.dependencies && + !schema.$_terms.keys && // null allows any keys + !schema.$_terms.patterns && + !schema.$_terms.externals) { - if (!invalids.length) { - return value; - } + return; + } - return helpers.error('string.email', { value, invalids }); - } - }, + // Shallow clone value - guid: { - alias: 'uuid', - method(options = {}) { + value = internals.clone(value, prefs); + const errors = []; - Common.assertOptions(options, ['version', 'separator']); + // Rename keys - let versionNumbers = ''; + if (schema.$_terms.renames && + !internals.rename(schema, value, state, prefs, errors)) { - if (options.version) { - const versions = [].concat(options.version); + return { value, errors }; + } - Assert(versions.length >= 1, 'version must have at least 1 valid version specified'); - const set = new Set(); + // Anything allowed - for (let i = 0; i < versions.length; ++i) { - const version = versions[i]; - Assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); - const versionNumber = internals.guidVersions[version.toLowerCase()]; - Assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', ')); - Assert(!set.has(versionNumber), 'version at position ' + i + ' must not be a duplicate'); + if (!schema.$_terms.keys && // null allows any keys + !schema.$_terms.patterns && + !schema.$_terms.dependencies) { - versionNumbers += versionNumber; - set.add(versionNumber); - } - } + return { value, errors }; + } - Assert(internals.guidSeparators.has(options.separator), 'separator must be one of true, false, "-", or ":"'); - const separator = options.separator === undefined ? '[:-]?' : - options.separator === true ? '[:-]' : - options.separator === false ? '[]?' : `\\${options.separator}`; + // Defined keys - const regex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}(${separator})[0-9A-F]{4}\\2?[${versionNumbers || '0-9A-F'}][0-9A-F]{3}\\2?[${versionNumbers ? '89AB' : '0-9A-F'}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`, 'i'); + const unprocessed = new Set(Object.keys(value)); - return this.$_addRule({ name: 'guid', args: { options }, regex }); - }, - validate(value, helpers, args, { regex }) { + if (schema.$_terms.keys) { + const ancestors = [value, ...state.ancestors]; - const results = regex.exec(value); + for (const child of schema.$_terms.keys) { + const key = child.key; + const item = value[key]; - if (!results) { - return helpers.error('string.guid'); - } + unprocessed.delete(key); - // Matching braces + const localState = state.localize([...state.path, key], ancestors, child); + const result = child.schema.$_validate(item, localState, prefs); - if (internals.guidBrackets[results[1]] !== results[results.length - 1]) { - return helpers.error('string.guid'); + if (result.errors) { + if (prefs.abortEarly) { + return { value, errors: result.errors }; + } + + if (result.value !== undefined) { + value[key] = result.value; + } + + errors.push(...result.errors); } + else if (child.schema._flags.result === 'strip' || + result.value === undefined && item !== undefined) { - return value; + delete value[key]; + } + else if (result.value !== undefined) { + value[key] = result.value; + } } - }, + } - hex: { - method(options = {}) { + // Unknown keys - Common.assertOptions(options, ['byteAligned']); + if (unprocessed.size || + schema._flags._hasPatternMatch) { - options = { byteAligned: false, ...options }; - Assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean'); + const early = internals.unknown(schema, value, unprocessed, errors, state, prefs); + if (early) { + return early; + } + } - return this.$_addRule({ name: 'hex', args: { options } }); - }, - validate(value, helpers, { options }) { + // Validate dependencies - if (!internals.hexRegex.test(value)) { - return helpers.error('string.hex'); + if (schema.$_terms.dependencies) { + for (const dep of schema.$_terms.dependencies) { + if ( + dep.key !== null && + internals.isPresent(dep.options)(dep.key.resolve(value, state, prefs, null, { shadow: false })) === false + ) { + + continue; } - if (options.byteAligned && - value.length % 2 !== 0) { + const failed = internals.dependencies[dep.rel](schema, dep, value, state, prefs); + if (failed) { + const report = schema.$_createError(failed.code, value, failed.context, state, prefs); + if (prefs.abortEarly) { + return { value, errors: report }; + } - return helpers.error('string.hexAlign'); + errors.push(report); } - - return value; } - }, + } - hostname: { - method() { + return { value, errors }; + }, - return this.$_addRule('hostname'); - }, - validate(value, helpers) { + rules: { - if (Domain.isValid(value, { minDomainSegments: 1 }) || - internals.ipRegex.test(value)) { + and: { + method(...peers /*, [options] */) { - return value; - } + Common.verifyFlat(peers, 'and'); - return helpers.error('string.hostname'); + return internals.dependency(this, 'and', null, peers); } }, - insensitive: { - method() { + append: { + method(schema) { - return this.$_setFlag('insensitive', true); + if (schema === null || + schema === undefined || + Object.keys(schema).length === 0) { + + return this; + } + + return this.keys(schema); } }, - ip: { - method(options = {}) { + assert: { + method(subject, schema, message) { - Common.assertOptions(options, ['cidr', 'version']); + if (!Template.isTemplate(subject)) { + subject = Compile.ref(subject); + } - const { cidr, versions, regex } = Ip.regex(options); - const version = options.version ? versions : undefined; - return this.$_addRule({ name: 'ip', args: { options: { cidr, version } }, regex }); + Assert(message === undefined || typeof message === 'string', 'Message must be a string'); + + schema = this.$_compile(schema, { appendPath: true }); + + const obj = this.$_addRule({ name: 'assert', args: { subject, schema, message } }); + obj.$_mutateRegister(subject); + obj.$_mutateRegister(schema); + return obj; }, - validate(value, helpers, { options }, { regex }) { + validate(value, { error, prefs, state }, { subject, schema, message }) { - if (regex.test(value)) { + const about = subject.resolve(value, state, prefs); + const path = Ref.isRef(subject) ? subject.absolute(state) : []; + if (schema.$_match(about, state.localize(path, [value, ...state.ancestors], schema), prefs)) { return value; } - if (options.version) { - return helpers.error('string.ipVersion', { value, cidr: options.cidr, version: options.version }); - } - - return helpers.error('string.ip', { value, cidr: options.cidr }); - } + return error('object.assert', { subject, message }); + }, + args: ['subject', 'schema', 'message'], + multi: true }, - isoDate: { - method() { + instance: { + method(constructor, name) { - return this.$_addRule('isoDate'); + Assert(typeof constructor === 'function', 'constructor must be a function'); + + name = name || constructor.name; + + return this.$_addRule({ name: 'instance', args: { constructor, name } }); }, - validate(value, { error }) { + validate(value, helpers, { constructor, name }) { - if (internals.isoDate(value)) { + if (value instanceof constructor) { return value; } - return error('string.isoDate'); - } + return helpers.error('object.instance', { type: name, value }); + }, + args: ['constructor', 'name'] }, - isoDuration: { - method() { + keys: { + method(schema) { - return this.$_addRule('isoDuration'); - }, - validate(value, helpers) { + Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object'); + Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema'); - if (internals.isoDurationRegex.test(value)) { - return value; + const obj = this.clone(); + + if (!schema) { // Allow all + obj.$_terms.keys = null; + } + else if (!Object.keys(schema).length) { // Allow none + obj.$_terms.keys = new internals.Keys(); + } + else { + obj.$_terms.keys = obj.$_terms.keys ? obj.$_terms.keys.filter((child) => !schema.hasOwnProperty(child.key)) : new internals.Keys(); + for (const key in schema) { + Common.tryWithPath(() => obj.$_terms.keys.push({ key, schema: this.$_compile(schema[key]) }), key); + } } - return helpers.error('string.isoDuration'); + return obj.$_mutateRebuild(); } }, length: { - method(limit, encoding) { + method(limit) { - return internals.length(this, 'length', limit, '=', encoding); + return this.$_addRule({ name: 'length', args: { limit }, operator: '=' }); }, - validate(value, helpers, { limit, encoding }, { name, operator, args }) { + validate(value, helpers, { limit }, { name, operator, args }) { - const length = encoding ? Buffer && Buffer.byteLength(value, encoding) : value.length; // $lab:coverage:ignore$ - if (Common.compare(length, limit, operator)) { + if (Common.compare(Object.keys(value).length, limit, operator)) { return value; } - return helpers.error('string.' + name, { limit: args.limit, value, encoding }); + return helpers.error('object.' + name, { limit: args.limit, value }); }, args: [ { @@ -29728,196 +29692,218 @@ module.exports = Any.extend({ ref: true, assert: Common.limit, message: 'must be a positive integer' - }, - 'encoding' + } ] }, - lowercase: { - method() { + max: { + method(limit) { - return this.case('lower'); + return this.$_addRule({ name: 'max', method: 'length', args: { limit }, operator: '<=' }); } }, - max: { - method(limit, encoding) { + min: { + method(limit) { - return internals.length(this, 'max', limit, '<=', encoding); - }, - args: ['limit', 'encoding'] + return this.$_addRule({ name: 'min', method: 'length', args: { limit }, operator: '>=' }); + } }, - min: { - method(limit, encoding) { + nand: { + method(...peers /*, [options] */) { - return internals.length(this, 'min', limit, '>=', encoding); - }, - args: ['limit', 'encoding'] + Common.verifyFlat(peers, 'nand'); + + return internals.dependency(this, 'nand', null, peers); + } }, - normalize: { - method(form = 'NFC') { + or: { + method(...peers /*, [options] */) { - Assert(internals.normalizationForms.includes(form), 'normalization form must be one of ' + internals.normalizationForms.join(', ')); + Common.verifyFlat(peers, 'or'); - return this.$_addRule({ name: 'normalize', args: { form } }); - }, - validate(value, { error }, { form }) { + return internals.dependency(this, 'or', null, peers); + } + }, - if (value === value.normalize(form)) { - return value; - } + oxor: { + method(...peers /*, [options] */) { - return error('string.normalize', { value, form }); - }, - convert: true + return internals.dependency(this, 'oxor', null, peers); + } }, pattern: { - alias: 'regex', - method(regex, options = {}) { + method(pattern, schema, options = {}) { - Assert(regex instanceof RegExp, 'regex must be a RegExp'); - Assert(!regex.flags.includes('g') && !regex.flags.includes('y'), 'regex should not use global or sticky mode'); + const isRegExp = pattern instanceof RegExp; + if (!isRegExp) { + pattern = this.$_compile(pattern, { appendPath: true }); + } - if (typeof options === 'string') { - options = { name: options }; + Assert(schema !== undefined, 'Invalid rule'); + Common.assertOptions(options, ['fallthrough', 'matches']); + + if (isRegExp) { + Assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); } - Common.assertOptions(options, ['invert', 'name']); + schema = this.$_compile(schema, { appendPath: true }); - const errorCode = ['string.pattern', options.invert ? '.invert' : '', options.name ? '.name' : '.base'].join(''); - return this.$_addRule({ name: 'pattern', args: { regex, options }, errorCode }); - }, - validate(value, helpers, { regex, options }, { errorCode }) { + const obj = this.clone(); + obj.$_terms.patterns = obj.$_terms.patterns || []; + const config = { [isRegExp ? 'regex' : 'schema']: pattern, rule: schema }; + if (options.matches) { + config.matches = this.$_compile(options.matches); + if (config.matches.type !== 'array') { + config.matches = config.matches.$_root.array().items(config.matches); + } - const patternMatch = regex.test(value); + obj.$_mutateRegister(config.matches); + obj.$_setFlag('_hasPatternMatch', true, { clone: false }); + } - if (patternMatch ^ options.invert) { - return value; + if (options.fallthrough) { + config.fallthrough = true; } - return helpers.error(errorCode, { name: options.name, regex, value }); - }, - args: ['regex', 'options'], - multi: true + obj.$_terms.patterns.push(config); + obj.$_mutateRegister(schema); + return obj; + } }, - replace: { - method(pattern, replacement) { - - if (typeof pattern === 'string') { - pattern = new RegExp(EscapeRegex(pattern), 'g'); - } - - Assert(pattern instanceof RegExp, 'pattern must be a RegExp'); - Assert(typeof replacement === 'string', 'replacement must be a String'); + ref: { + method() { - const obj = this.clone(); + return this.$_addRule('ref'); + }, + validate(value, helpers) { - if (!obj.$_terms.replacements) { - obj.$_terms.replacements = []; + if (Ref.isRef(value)) { + return value; } - obj.$_terms.replacements.push({ pattern, replacement }); - return obj; + return helpers.error('object.refType', { value }); } }, - token: { + regex: { method() { - return this.$_addRule('token'); + return this.$_addRule('regex'); }, validate(value, helpers) { - if (/^\w+$/.test(value)) { + if (value instanceof RegExp) { return value; } - return helpers.error('string.token'); + return helpers.error('object.regex', { value }); } }, - trim: { - method(enabled = true) { + rename: { + method(from, to, options = {}) { - Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); + Assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument'); + Assert(typeof to === 'string' || to instanceof Template, 'Invalid rename to argument'); + Assert(to !== from, 'Cannot rename key to same name:', from); - return this.$_addRule({ name: 'trim', args: { enabled } }); + Common.assertOptions(options, ['alias', 'ignoreUndefined', 'override', 'multiple']); + + const obj = this.clone(); + + obj.$_terms.renames = obj.$_terms.renames || []; + for (const rename of obj.$_terms.renames) { + Assert(rename.from !== from, 'Cannot rename the same key multiple times'); + } + + if (to instanceof Template) { + obj.$_mutateRegister(to); + } + + obj.$_terms.renames.push({ + from, + to, + options: ApplyToDefaults(internals.renameDefaults, options) + }); + + return obj; + } + }, + + schema: { + method(type = 'any') { + + return this.$_addRule({ name: 'schema', args: { type } }); }, - validate(value, helpers, { enabled }) { + validate(value, helpers, { type }) { - if (!enabled || - value === value.trim()) { + if (Common.isSchema(value) && + (type === 'any' || value.type === type)) { return value; } - return helpers.error('string.trim'); - }, - convert: true + return helpers.error('object.schema', { type }); + } }, - truncate: { - method(enabled = true) { - - Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); + unknown: { + method(allow) { - return this.$_setFlag('truncate', enabled); + return this.$_setFlag('unknown', allow !== false); } }, - uppercase: { - method() { + with: { + method(key, peers, options = {}) { - return this.case('upper'); + return internals.dependency(this, 'with', key, peers, options); } }, - uri: { - method(options = {}) { + without: { + method(key, peers, options = {}) { - Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme']); + return internals.dependency(this, 'without', key, peers, options); + } + }, - if (options.domain) { - Common.assertOptions(options.domain, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); - } + xor: { + method(...peers /*, [options] */) { - const { regex, scheme } = Uri.regex(options); - const domain = options.domain ? internals.addressOptions(options.domain) : null; - return this.$_addRule({ name: 'uri', args: { options }, regex, domain, scheme }); - }, - validate(value, helpers, { options }, { regex, domain, scheme }) { + Common.verifyFlat(peers, 'xor'); - if (['http:/', 'https:/'].includes(value)) { // scheme:/ is technically valid but makes no sense - return helpers.error('string.uri'); - } + return internals.dependency(this, 'xor', null, peers); + } + } + }, - const match = regex.exec(value); - if (match) { - const matched = match[1] || match[2]; - if (domain && - (!options.allowRelative || matched) && - !Domain.isValid(matched, domain)) { + overrides: { - return helpers.error('string.domain', { value: matched }); - } + default(value, options) { - return value; - } + if (value === undefined) { + value = Common.symbols.deepDefault; + } - if (options.relativeOnly) { - return helpers.error('string.uriRelativeOnly'); - } + return this.$_parent('default', value, options); + } + }, - if (options.scheme) { - return helpers.error('string.uriCustomScheme', { scheme, value }); - } + rebuild(schema) { - return helpers.error('string.uri'); + if (schema.$_terms.keys) { + const topo = new Topo.Sorter(); + for (const child of schema.$_terms.keys) { + Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key }), child.key); } + + schema.$_terms.keys = new internals.Keys(...topo.nodes); } }, @@ -29925,9 +29911,25 @@ module.exports = Any.extend({ build(obj, desc) { - if (desc.replacements) { - for (const { pattern, replacement } of desc.replacements) { - obj = obj.replace(pattern, replacement); + if (desc.keys) { + obj = obj.keys(desc.keys); + } + + if (desc.dependencies) { + for (const { rel, key = null, peers, options } of desc.dependencies) { + obj = internals.dependency(obj, rel, key, peers, options); + } + } + + if (desc.patterns) { + for (const { regex, schema, rule, fallthrough, matches } of desc.patterns) { + obj = obj.pattern(regex || schema, rule, { fallthrough, matches }); + } + } + + if (desc.renames) { + for (const { from, to, options } of desc.renames) { + obj = obj.rename(from, to, options); } } @@ -29936,20290 +29938,20330 @@ module.exports = Any.extend({ }, messages: { - 'string.alphanum': '{{#label}} must only contain alpha-numeric characters', - 'string.base': '{{#label}} must be a string', - 'string.base64': '{{#label}} must be a valid base64 string', - 'string.creditCard': '{{#label}} must be a credit card', - 'string.dataUri': '{{#label}} must be a valid dataUri string', - 'string.domain': '{{#label}} must contain a valid domain name', - 'string.email': '{{#label}} must be a valid email', - 'string.empty': '{{#label}} is not allowed to be empty', - 'string.guid': '{{#label}} must be a valid GUID', - 'string.hex': '{{#label}} must only contain hexadecimal characters', - 'string.hexAlign': '{{#label}} hex decoded representation must be byte aligned', - 'string.hostname': '{{#label}} must be a valid hostname', - 'string.ip': '{{#label}} must be a valid ip address with a {{#cidr}} CIDR', - 'string.ipVersion': '{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR', - 'string.isoDate': '{{#label}} must be in iso format', - 'string.isoDuration': '{{#label}} must be a valid ISO 8601 duration', - 'string.length': '{{#label}} length must be {{#limit}} characters long', - 'string.lowercase': '{{#label}} must only contain lowercase characters', - 'string.max': '{{#label}} length must be less than or equal to {{#limit}} characters long', - 'string.min': '{{#label}} length must be at least {{#limit}} characters long', - 'string.normalize': '{{#label}} must be unicode normalized in the {{#form}} form', - 'string.token': '{{#label}} must only contain alpha-numeric and underscore characters', - 'string.pattern.base': '{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}', - 'string.pattern.name': '{{#label}} with value {:[.]} fails to match the {{#name}} pattern', - 'string.pattern.invert.base': '{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}', - 'string.pattern.invert.name': '{{#label}} with value {:[.]} matches the inverted {{#name}} pattern', - 'string.trim': '{{#label}} must not have leading or trailing whitespace', - 'string.uri': '{{#label}} must be a valid uri', - 'string.uriCustomScheme': '{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern', - 'string.uriRelativeOnly': '{{#label}} must be a valid relative uri', - 'string.uppercase': '{{#label}} must only contain uppercase characters' + 'object.and': '{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}', + 'object.assert': '{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}', + 'object.base': '{{#label}} must be of type {{#type}}', + 'object.instance': '{{#label}} must be an instance of {{:#type}}', + 'object.length': '{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}', + 'object.max': '{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}', + 'object.min': '{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}', + 'object.missing': '{{#label}} must contain at least one of {{#peersWithLabels}}', + 'object.nand': '{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}', + 'object.oxor': '{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}', + 'object.pattern.match': '{{#label}} keys failed to match pattern requirements', + 'object.refType': '{{#label}} must be a Joi reference', + 'object.regex': '{{#label}} must be a RegExp object', + 'object.rename.multiple': '{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}', + 'object.rename.override': '{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists', + 'object.schema': '{{#label}} must be a Joi schema of {{#type}} type', + 'object.unknown': '{{#label}} is not allowed', + 'object.with': '{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}', + 'object.without': '{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}', + 'object.xor': '{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}' } }); // Helpers -internals.addressOptions = function (options) { - - if (!options) { - return options; - } - - // minDomainSegments - - Assert(options.minDomainSegments === undefined || - Number.isSafeInteger(options.minDomainSegments) && options.minDomainSegments > 0, 'minDomainSegments must be a positive integer'); - - // maxDomainSegments - - Assert(options.maxDomainSegments === undefined || - Number.isSafeInteger(options.maxDomainSegments) && options.maxDomainSegments > 0, 'maxDomainSegments must be a positive integer'); - - // tlds - - if (options.tlds === false) { - return options; - } - - if (options.tlds === true || - options.tlds === undefined) { - - Assert(internals.tlds, 'Built-in TLD list disabled'); - return Object.assign({}, options, internals.tlds); - } +internals.clone = function (value, prefs) { - Assert(typeof options.tlds === 'object', 'tlds must be true, false, or an object'); + // Object - const deny = options.tlds.deny; - if (deny) { - if (Array.isArray(deny)) { - options = Object.assign({}, options, { tlds: { deny: new Set(deny) } }); + if (typeof value === 'object') { + if (prefs.nonEnumerables) { + return Clone(value, { shallow: true }); } - Assert(options.tlds.deny instanceof Set, 'tlds.deny must be an array, Set, or boolean'); - Assert(!options.tlds.allow, 'Cannot specify both tlds.allow and tlds.deny lists'); - internals.validateTlds(options.tlds.deny, 'tlds.deny'); - return options; - } - - const allow = options.tlds.allow; - if (!allow) { - return options; - } - - if (allow === true) { - Assert(internals.tlds, 'Built-in TLD list disabled'); - return Object.assign({}, options, internals.tlds); - } - - if (Array.isArray(allow)) { - options = Object.assign({}, options, { tlds: { allow: new Set(allow) } }); + const clone = Object.create(Object.getPrototypeOf(value)); + Object.assign(clone, value); + return clone; } - Assert(options.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean'); - internals.validateTlds(options.tlds.allow, 'tlds.allow'); - return options; -}; + // Function + const clone = function (...args) { -internals.validateTlds = function (set, source) { + return value.apply(this, args); + }; - for (const tld of set) { - Assert(Domain.isValid(tld, { minDomainSegments: 1, maxDomainSegments: 1 }), `${source} must contain valid top level domain names`); - } + clone.prototype = Clone(value.prototype); + Object.defineProperty(clone, 'name', { value: value.name, writable: false }); + Object.defineProperty(clone, 'length', { value: value.length, writable: false }); + Object.assign(clone, value); + return clone; }; -internals.isoDate = function (value) { +internals.dependency = function (schema, rel, key, peers, options) { - if (!Common.isIsoDate(value)) { - return null; - } + Assert(key === null || typeof key === 'string', rel, 'key must be a strings'); - if (/.*T.*[+-]\d\d$/.test(value)) { // Add missing trailing zeros to timeshift - value += '00'; - } + // Extract options from peers array - const date = new Date(value); - if (isNaN(date.getTime())) { - return null; + if (!options) { + options = peers.length > 1 && typeof peers[peers.length - 1] === 'object' ? peers.pop() : {}; } - return date.toISOString(); -}; - - -internals.length = function (schema, name, limit, operator, encoding) { - - Assert(!encoding || Buffer && Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); // $lab:coverage:ignore$ - - return schema.$_addRule({ name, method: 'length', args: { limit, encoding }, operator }); -}; - - -/***/ }), - -/***/ 40971: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); + Common.assertOptions(options, ['separator', 'isPresent']); -const Any = __nccwpck_require__(9512); + peers = [].concat(peers); + // Cast peer paths -const internals = {}; + const separator = Common.default(options.separator, '.'); + const paths = []; + for (const peer of peers) { + Assert(typeof peer === 'string', rel, 'peers must be strings'); + paths.push(Compile.ref(peer, { separator, ancestor: 0, prefix: false })); + } + // Cast key -internals.Map = class extends Map { + if (key !== null) { + key = Compile.ref(key, { separator, ancestor: 0, prefix: false }); + } - slice() { + // Add rule - return new internals.Map(this); - } + const obj = schema.clone(); + obj.$_terms.dependencies = obj.$_terms.dependencies || []; + obj.$_terms.dependencies.push(new internals.Dependency(rel, key, paths, peers, options)); + return obj; }; -module.exports = Any.extend({ +internals.dependencies = { - type: 'symbol', + and(schema, dep, value, state, prefs) { - terms: { + const missing = []; + const present = []; + const count = dep.peers.length; + const isPresent = internals.isPresent(dep.options); + for (const peer of dep.peers) { + if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false })) === false) { + missing.push(peer.key); + } + else { + present.push(peer.key); + } + } - map: { init: new internals.Map() } + if (missing.length !== count && + present.length !== count) { + + return { + code: 'object.and', + context: { + present, + presentWithLabels: internals.keysToLabels(schema, present), + missing, + missingWithLabels: internals.keysToLabels(schema, missing) + } + }; + } }, - coerce: { - method(value, { schema, error }) { + nand(schema, dep, value, state, prefs) { - const lookup = schema.$_terms.map.get(value); - if (lookup) { - value = lookup; + const present = []; + const isPresent = internals.isPresent(dep.options); + for (const peer of dep.peers) { + if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { + present.push(peer.key); } + } - if (!schema._flags.only || - typeof value === 'symbol') { + if (present.length !== dep.peers.length) { + return; + } - return { value }; + const main = dep.paths[0]; + const values = dep.paths.slice(1); + return { + code: 'object.nand', + context: { + main, + mainWithLabel: internals.keysToLabels(schema, main), + peers: values, + peersWithLabels: internals.keysToLabels(schema, values) } - - return { value, errors: error('symbol.map', { map: schema.$_terms.map }) }; - } + }; }, - validate(value, { error }) { + or(schema, dep, value, state, prefs) { - if (typeof value !== 'symbol') { - return { value, errors: error('symbol.base') }; + const isPresent = internals.isPresent(dep.options); + for (const peer of dep.peers) { + if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { + return; + } } + + return { + code: 'object.missing', + context: { + peers: dep.paths, + peersWithLabels: internals.keysToLabels(schema, dep.paths) + } + }; }, - rules: { - map: { - method(iterable) { + oxor(schema, dep, value, state, prefs) { - if (iterable && - !iterable[Symbol.iterator] && - typeof iterable === 'object') { + const present = []; + const isPresent = internals.isPresent(dep.options); + for (const peer of dep.peers) { + if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { + present.push(peer.key); + } + } - iterable = Object.entries(iterable); - } + if (!present.length || + present.length === 1) { - Assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object'); + return; + } - const obj = this.clone(); + const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; + context.present = present; + context.presentWithLabels = internals.keysToLabels(schema, present); + return { code: 'object.oxor', context }; + }, - const symbols = []; - for (const entry of iterable) { - Assert(entry && entry[Symbol.iterator], 'Entry must be an iterable'); - const [key, value] = entry; + with(schema, dep, value, state, prefs) { - Assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be of type object, function, or Symbol'); - Assert(typeof value === 'symbol', 'Value must be a Symbol'); + const isPresent = internals.isPresent(dep.options); + for (const peer of dep.peers) { + if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false })) === false) { + return { + code: 'object.with', + context: { + main: dep.key.key, + mainWithLabel: internals.keysToLabels(schema, dep.key.key), + peer: peer.key, + peerWithLabel: internals.keysToLabels(schema, peer.key) + } + }; + } + } + }, - obj.$_terms.map.set(key, value); - symbols.push(value); - } + without(schema, dep, value, state, prefs) { - return obj.valid(...symbols); + const isPresent = internals.isPresent(dep.options); + for (const peer of dep.peers) { + if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { + return { + code: 'object.without', + context: { + main: dep.key.key, + mainWithLabel: internals.keysToLabels(schema, dep.key.key), + peer: peer.key, + peerWithLabel: internals.keysToLabels(schema, peer.key) + } + }; } } }, - manifest: { - - build(obj, desc) { + xor(schema, dep, value, state, prefs) { - if (desc.map) { - obj = obj.map(desc.map); + const present = []; + const isPresent = internals.isPresent(dep.options); + for (const peer of dep.peers) { + if (isPresent(peer.resolve(value, state, prefs, null, { shadow: false }))) { + present.push(peer.key); } + } - return obj; + if (present.length === 1) { + return; } - }, - messages: { - 'symbol.base': '{{#label}} must be a symbol', - 'symbol.map': '{{#label}} must be one of {{#map}}' + const context = { peers: dep.paths, peersWithLabels: internals.keysToLabels(schema, dep.paths) }; + if (present.length === 0) { + return { code: 'object.missing', context }; + } + + context.present = present; + context.presentWithLabels = internals.keysToLabels(schema, present); + return { code: 'object.xor', context }; } -}); +}; -/***/ }), +internals.keysToLabels = function (schema, keys) { -/***/ 91804: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (Array.isArray(keys)) { + return keys.map((key) => schema.$_mapLabels(key)); + } -"use strict"; + return schema.$_mapLabels(keys); +}; -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Ignore = __nccwpck_require__(12887); -const Reach = __nccwpck_require__(18891); +internals.isPresent = function (options) { -const Common = __nccwpck_require__(72448); -const Errors = __nccwpck_require__(69490); -const State = __nccwpck_require__(73634); + return typeof options.isPresent === 'function' ? options.isPresent : (resolved) => resolved !== undefined; +}; -const internals = { - result: Symbol('result') -}; +internals.rename = function (schema, value, state, prefs, errors) { + const renamed = {}; + for (const rename of schema.$_terms.renames) { + const matches = []; + const pattern = typeof rename.from !== 'string'; -exports.entry = function (value, schema, prefs) { + if (!pattern) { + if (Object.prototype.hasOwnProperty.call(value, rename.from) && + (value[rename.from] !== undefined || !rename.options.ignoreUndefined)) { - let settings = Common.defaults; - if (prefs) { - Assert(prefs.warnings === undefined, 'Cannot override warnings preference in synchronous validation'); - Assert(prefs.artifacts === undefined, 'Cannot override artifacts preference in synchronous validation'); - settings = Common.preferences(Common.defaults, prefs); - } + matches.push(rename); + } + } + else { + for (const from in value) { + if (value[from] === undefined && + rename.options.ignoreUndefined) { - const result = internals.entry(value, schema, settings); - Assert(!result.mainstay.externals.length, 'Schema with external rules must use validateAsync()'); - const outcome = { value: result.value }; + continue; + } - if (result.error) { - outcome.error = result.error; - } + if (from === rename.to) { + continue; + } - if (result.mainstay.warnings.length) { - outcome.warning = Errors.details(result.mainstay.warnings); - } + const match = rename.from.exec(from); + if (!match) { + continue; + } - if (result.mainstay.debug) { - outcome.debug = result.mainstay.debug; - } + matches.push({ from, to: rename.to, match }); + } + } - if (result.mainstay.artifacts) { - outcome.artifacts = result.mainstay.artifacts; - } + for (const match of matches) { + const from = match.from; + let to = match.to; + if (to instanceof Template) { + to = to.render(value, state, prefs, match.match); + } - return outcome; -}; + if (from === to) { + continue; + } + if (!rename.options.multiple && + renamed[to]) { -exports.entryAsync = async function (value, schema, prefs) { + errors.push(schema.$_createError('object.rename.multiple', value, { from, to, pattern }, state, prefs)); + if (prefs.abortEarly) { + return false; + } + } - let settings = Common.defaults; - if (prefs) { - settings = Common.preferences(Common.defaults, prefs); - } + if (Object.prototype.hasOwnProperty.call(value, to) && + !rename.options.override && + !renamed[to]) { - const result = internals.entry(value, schema, settings); - const mainstay = result.mainstay; - if (result.error) { - if (mainstay.debug) { - result.error.debug = mainstay.debug; - } + errors.push(schema.$_createError('object.rename.override', value, { from, to, pattern }, state, prefs)); + if (prefs.abortEarly) { + return false; + } + } - throw result.error; + if (value[from] === undefined) { + delete value[to]; + } + else { + value[to] = value[from]; + } + + renamed[to] = true; + + if (!rename.options.alias) { + delete value[from]; + } + } } - if (mainstay.externals.length) { - let root = result.value; - const errors = []; - for (const external of mainstay.externals) { - const path = external.state.path; - const linked = external.schema.type === 'link' ? mainstay.links.get(external.schema) : null; - let node = root; - let key; - let parent; + return true; +}; - const ancestors = path.length ? [root] : []; - const original = path.length ? Reach(value, path) : value; - if (path.length) { - key = path[path.length - 1]; +internals.unknown = function (schema, value, unprocessed, errors, state, prefs) { - let current = root; - for (const segment of path.slice(0, -1)) { - current = current[segment]; - ancestors.unshift(current); - } + if (schema.$_terms.patterns) { + let hasMatches = false; + const matches = schema.$_terms.patterns.map((pattern) => { - parent = ancestors[0]; - node = parent[key]; + if (pattern.matches) { + hasMatches = true; + return []; } + }); - try { - const createError = (code, local) => (linked || external.schema).$_createError(code, node, local, external.state, settings); - const output = await external.method(node, { - schema: external.schema, - linked, - state: external.state, - prefs, - original, - error: createError, - errorsArray: internals.errorsArray, - warn: (code, local) => mainstay.warnings.push((linked || external.schema).$_createError(code, node, local, external.state, settings)), - message: (messages, local) => (linked || external.schema).$_createError('external', node, local, external.state, settings, { messages }) - }); + const ancestors = [value, ...state.ancestors]; - if (output === undefined || - output === node) { + for (const key of unprocessed) { + const item = value[key]; + const path = [...state.path, key]; - continue; + for (let i = 0; i < schema.$_terms.patterns.length; ++i) { + const pattern = schema.$_terms.patterns[i]; + if (pattern.regex) { + const match = pattern.regex.test(key); + state.mainstay.tracer.debug(state, 'rule', `pattern.${i}`, match ? 'pass' : 'error'); + if (!match) { + continue; + } } - - if (output instanceof Errors.Report) { - mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error'); - errors.push(output); - - if (settings.abortEarly) { - break; + else { + if (!pattern.schema.$_match(key, state.nest(pattern.schema, `pattern.${i}`), prefs)) { + continue; } - - continue; } - if (Array.isArray(output) && - output[Common.symbols.errors]) { - mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error'); - errors.push(...output); + unprocessed.delete(key); - if (settings.abortEarly) { - break; + const localState = state.localize(path, ancestors, { schema: pattern.rule, key }); + const result = pattern.rule.$_validate(item, localState, prefs); + if (result.errors) { + if (prefs.abortEarly) { + return { value, errors: result.errors }; } - continue; + errors.push(...result.errors); } - if (parent) { - mainstay.tracer.value(external.state, 'rule', node, output, 'external'); - parent[key] = output; - } - else { - mainstay.tracer.value(external.state, 'rule', root, output, 'external'); - root = output; - } - } - catch (err) { - if (settings.errors.label) { - err.message += ` (${(external.label)})`; // Change message to include path + if (pattern.matches) { + matches[i].push(key); } - throw err; + value[key] = result.value; + if (!pattern.fallthrough) { + break; + } } } - result.value = root; + // Validate pattern matches rules - if (errors.length) { - result.error = Errors.process(errors, value, settings); + if (hasMatches) { + for (let i = 0; i < matches.length; ++i) { + const match = matches[i]; + if (!match) { + continue; + } - if (mainstay.debug) { - result.error.debug = mainstay.debug; - } + const stpm = schema.$_terms.patterns[i].matches; + const localState = state.localize(state.path, ancestors, stpm); + const result = stpm.$_validate(match, localState, prefs); + if (result.errors) { + const details = Errors.details(result.errors, { override: false }); + details.matches = match; + const report = schema.$_createError('object.pattern.match', value, details, state, prefs); + if (prefs.abortEarly) { + return { value, errors: report }; + } - throw result.error; + errors.push(report); + } + } } } - if (!settings.warnings && - !settings.debug && - !settings.artifacts) { + if (!unprocessed.size || + !schema.$_terms.keys && !schema.$_terms.patterns) { // If no keys or patterns specified, unknown keys allowed - return result.value; + return; } - const outcome = { value: result.value }; - if (mainstay.warnings.length) { - outcome.warning = Errors.details(mainstay.warnings); - } + if (prefs.stripUnknown && typeof schema._flags.unknown === 'undefined' || + prefs.skipFunctions) { - if (mainstay.debug) { - outcome.debug = mainstay.debug; - } + const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false; - if (mainstay.artifacts) { - outcome.artifacts = mainstay.artifacts; + for (const key of unprocessed) { + if (stripUnknown) { + delete value[key]; + unprocessed.delete(key); + } + else if (typeof value[key] === 'function') { + unprocessed.delete(key); + } + } } - return outcome; -}; + const forbidUnknown = !Common.default(schema._flags.unknown, prefs.allowUnknown); + if (forbidUnknown) { + for (const unprocessedKey of unprocessed) { + const localState = state.localize([...state.path, unprocessedKey], []); + const report = schema.$_createError('object.unknown', value[unprocessedKey], { child: unprocessedKey }, localState, prefs, { flags: false }); + if (prefs.abortEarly) { + return { value, errors: report }; + } + errors.push(report); + } + } +}; -internals.Mainstay = class { - constructor(tracer, debug, links) { +internals.Dependency = class { - this.externals = []; - this.warnings = []; - this.tracer = tracer; - this.debug = debug; - this.links = links; - this.shadow = null; - this.artifacts = null; + constructor(rel, key, peers, paths, options) { - this._snapshots = []; + this.rel = rel; + this.key = key; + this.peers = peers; + this.paths = paths; + this.options = options; } - snapshot() { + describe() { - this._snapshots.push({ - externals: this.externals.slice(), - warnings: this.warnings.slice() - }); - } + const desc = { + rel: this.rel, + peers: this.paths + }; - restore() { + if (this.key !== null) { + desc.key = this.key.key; + } - const snapshot = this._snapshots.pop(); - this.externals = snapshot.externals; - this.warnings = snapshot.warnings; - } + if (this.peers[0].separator !== '.') { + desc.options = { ...desc.options, separator: this.peers[0].separator }; + } - commit() { + if (this.options.isPresent) { + desc.options = { ...desc.options, isPresent: this.options.isPresent }; + } - this._snapshots.pop(); + return desc; } }; -internals.entry = function (value, schema, prefs) { - - // Prepare state +internals.Keys = class extends Array { - const { tracer, cleanup } = internals.tracer(schema, prefs); - const debug = prefs.debug ? [] : null; - const links = schema._ids._schemaChain ? new Map() : null; - const mainstay = new internals.Mainstay(tracer, debug, links); - const schemas = schema._ids._schemaChain ? [{ schema }] : null; - const state = new State([], [], { mainstay, schemas }); + concat(source) { - // Validate value + const result = this.slice(); - const result = exports.validate(value, schema, state, prefs); + const keys = new Map(); + for (let i = 0; i < result.length; ++i) { + keys.set(result[i].key, i); + } - // Process value and errors + for (const item of source) { + const key = item.key; + const pos = keys.get(key); + if (pos !== undefined) { + result[pos] = { key, schema: result[pos].schema.concat(item.schema) }; + } + else { + result.push(item); + } + } - if (cleanup) { - schema.$_root.untrace(); + return result; } - - const error = Errors.process(result.errors, value, prefs); - return { value: result.value, error, mainstay }; }; -internals.tracer = function (schema, prefs) { +/***/ }), - if (schema.$_root._tracer) { - return { tracer: schema.$_root._tracer._register(schema) }; - } +/***/ 69869: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (prefs.debug) { - Assert(schema.$_root.trace, 'Debug mode not supported'); - return { tracer: schema.$_root.trace()._register(schema), cleanup: true }; - } +"use strict"; + + +const Assert = __nccwpck_require__(32718); + +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); +const Compile = __nccwpck_require__(3038); +const Errors = __nccwpck_require__(69490); + + +const internals = {}; - return { tracer: internals.ignore }; -}; +module.exports = Any.extend({ -exports.validate = function (value, schema, state, prefs, overrides = {}) { + type: 'link', - if (schema.$_terms.whens) { - schema = schema._generate(value, state, prefs).schema; - } + properties: { + schemaChain: true + }, - // Setup state and settings + terms: { - if (schema._preferences) { - prefs = internals.prefs(schema, prefs); - } + link: { init: null, manifest: 'single', register: false } + }, - // Cache + args(schema, ref) { - if (schema._cache && - prefs.cache) { + return schema.ref(ref); + }, - const result = schema._cache.get(value); - state.mainstay.tracer.debug(state, 'validate', 'cached', !!result); - if (result) { - return result; - } - } + validate(value, { schema, state, prefs }) { - // Helpers + Assert(schema.$_terms.link, 'Uninitialized link schema'); - const createError = (code, local, localState) => schema.$_createError(code, value, local, localState || state, prefs); - const helpers = { - original: value, - prefs, - schema, - state, - error: createError, - errorsArray: internals.errorsArray, - warn: (code, local, localState) => state.mainstay.warnings.push(createError(code, local, localState)), - message: (messages, local) => schema.$_createError('custom', value, local, state, prefs, { messages }) - }; + const linked = internals.generate(schema, value, state, prefs); + const ref = schema.$_terms.link[0].ref; + return linked.$_validate(value, state.nest(linked, `link:${ref.display}:${linked.type}`), prefs); + }, - // Prepare + generate(schema, value, state, prefs) { - state.mainstay.tracer.entry(schema, state); + return internals.generate(schema, value, state, prefs); + }, - const def = schema._definition; - if (def.prepare && - value !== undefined && - prefs.convert) { + rules: { - const prepared = def.prepare(value, helpers); - if (prepared) { - state.mainstay.tracer.value(state, 'prepare', value, prepared.value); - if (prepared.errors) { - return internals.finalize(prepared.value, [].concat(prepared.errors), helpers); // Prepare error always aborts early - } + ref: { + method(ref) { - value = prepared.value; - } - } + Assert(!this.$_terms.link, 'Cannot reinitialize schema'); - // Type coercion + ref = Compile.ref(ref); - if (def.coerce && - value !== undefined && - prefs.convert && - (!def.coerce.from || def.coerce.from.includes(typeof value))) { + Assert(ref.type === 'value' || ref.type === 'local', 'Invalid reference type:', ref.type); + Assert(ref.type === 'local' || ref.ancestor === 'root' || ref.ancestor > 0, 'Link cannot reference itself'); - const coerced = def.coerce.method(value, helpers); - if (coerced) { - state.mainstay.tracer.value(state, 'coerced', value, coerced.value); - if (coerced.errors) { - return internals.finalize(coerced.value, [].concat(coerced.errors), helpers); // Coerce error always aborts early + const obj = this.clone(); + obj.$_terms.link = [{ ref }]; + return obj; } + }, - value = coerced.value; + relative: { + method(enabled = true) { + + return this.$_setFlag('relative', enabled); + } } - } + }, - // Empty value + overrides: { - const empty = schema._flags.empty; - if (empty && - empty.$_match(internals.trim(value, schema), state.nest(empty), Common.defaults)) { + concat(source) { - state.mainstay.tracer.value(state, 'empty', value, undefined); - value = undefined; - } + Assert(this.$_terms.link, 'Uninitialized link schema'); + Assert(Common.isSchema(source), 'Invalid schema object'); + Assert(source.type !== 'link', 'Cannot merge type link with another link'); - // Presence requirements (required, optional, forbidden) + const obj = this.clone(); - const presence = overrides.presence || schema._flags.presence || (schema._flags._endedSwitch ? null : prefs.presence); - if (value === undefined) { - if (presence === 'forbidden') { - return internals.finalize(value, null, helpers); - } + if (!obj.$_terms.whens) { + obj.$_terms.whens = []; + } - if (presence === 'required') { - return internals.finalize(value, [schema.$_createError('any.required', value, null, state, prefs)], helpers); + obj.$_terms.whens.push({ concat: source }); + return obj.$_mutateRebuild(); } + }, - if (presence === 'optional') { - if (schema._flags.default !== Common.symbols.deepDefault) { - return internals.finalize(value, null, helpers); - } + manifest: { - state.mainstay.tracer.value(state, 'default', value, {}); - value = {}; + build(obj, desc) { + + Assert(desc.link, 'Invalid link description missing link'); + return obj.ref(desc.link); } } - else if (presence === 'forbidden') { - return internals.finalize(value, [schema.$_createError('any.unknown', value, null, state, prefs)], helpers); - } +}); - // Allowed values - const errors = []; +// Helpers - if (schema._valids) { - const match = schema._valids.get(value, state, prefs, schema._flags.insensitive); - if (match) { - if (prefs.convert) { - state.mainstay.tracer.value(state, 'valids', value, match.value); - value = match.value; - } +internals.generate = function (schema, value, state, prefs) { - state.mainstay.tracer.filter(schema, state, 'valid', match); - return internals.finalize(value, null, helpers); - } + let linked = state.mainstay.links.get(schema); + if (linked) { + return linked._generate(value, state, prefs).schema; + } - if (schema._flags.only) { - const report = schema.$_createError('any.only', value, { valids: schema._valids.values({ display: true }) }, state, prefs); - if (prefs.abortEarly) { - return internals.finalize(value, [report], helpers); - } + const ref = schema.$_terms.link[0].ref; + const { perspective, path } = internals.perspective(ref, state); + internals.assert(perspective, 'which is outside of schema boundaries', ref, schema, state, prefs); - errors.push(report); - } + try { + linked = path.length ? perspective.$_reach(path) : perspective; + } + catch (ignoreErr) { + internals.assert(false, 'to non-existing schema', ref, schema, state, prefs); } - // Denied values - - if (schema._invalids) { - const match = schema._invalids.get(value, state, prefs, schema._flags.insensitive); - if (match) { - state.mainstay.tracer.filter(schema, state, 'invalid', match); - const report = schema.$_createError('any.invalid', value, { invalids: schema._invalids.values({ display: true }) }, state, prefs); - if (prefs.abortEarly) { - return internals.finalize(value, [report], helpers); - } + internals.assert(linked.type !== 'link', 'which is another link', ref, schema, state, prefs); - errors.push(report); - } + if (!schema._flags.relative) { + state.mainstay.links.set(schema, linked); } - // Base type + return linked._generate(value, state, prefs).schema; +}; - if (def.validate) { - const base = def.validate(value, helpers); - if (base) { - state.mainstay.tracer.value(state, 'base', value, base.value); - value = base.value; - if (base.errors) { - if (!Array.isArray(base.errors)) { - errors.push(base.errors); - return internals.finalize(value, errors, helpers); // Base error always aborts early - } +internals.perspective = function (ref, state) { - if (base.errors.length) { - errors.push(...base.errors); - return internals.finalize(value, errors, helpers); // Base error always aborts early + if (ref.type === 'local') { + for (const { schema, key } of state.schemas) { // From parent to root + const id = schema._flags.id || key; + if (id === ref.path[0]) { + return { perspective: schema, path: ref.path.slice(1) }; + } + + if (schema.$_terms.shared) { + for (const shared of schema.$_terms.shared) { + if (shared._flags.id === ref.path[0]) { + return { perspective: shared, path: ref.path.slice(1) }; + } } } } + + return { perspective: null, path: null }; } - // Validate tests + if (ref.ancestor === 'root') { + return { perspective: state.schemas[state.schemas.length - 1].schema, path: ref.path }; + } - if (!schema._rules.length) { - return internals.finalize(value, errors, helpers); + return { perspective: state.schemas[ref.ancestor] && state.schemas[ref.ancestor].schema, path: ref.path }; +}; + + +internals.assert = function (condition, message, ref, schema, state, prefs) { + + if (condition) { // Manual check to avoid generating error message on success + return; } - return internals.rules(value, errors, helpers); + Assert(false, `"${Errors.label(schema._flags, state, prefs)}" contains link reference "${ref.display}" ${message}`); }; -internals.rules = function (value, errors, helpers) { +/***/ }), - const { schema, state, prefs } = helpers; +/***/ 15855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (const rule of schema._rules) { - const definition = schema._definition.rules[rule.method]; +"use strict"; - // Skip rules that are also applied in coerce step - if (definition.convert && - prefs.convert) { +const Assert = __nccwpck_require__(32718); - state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'full'); - continue; - } +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); - // Resolve references - let ret; - let args = rule.args; - if (rule._resolve.length) { - args = Object.assign({}, args); // Shallow copy - for (const key of rule._resolve) { - const resolver = definition.argsByName.get(key); +const internals = { + numberRx: /^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i, + precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/, + exponentialPartRegex: /[eE][+-]?\d+$/, + leadingSignAndZerosRegex: /^[+-]?(0*)?/, + dotRegex: /\./, + trailingZerosRegex: /0+$/, + decimalPlaces(value) { - const resolved = args[key].resolve(value, state, prefs); - const normalized = resolver.normalize ? resolver.normalize(resolved) : resolved; + const str = value.toString(); + const dindex = str.indexOf('.'); + const eindex = str.indexOf('e'); + return ( + (dindex < 0 ? 0 : (eindex < 0 ? str.length : eindex) - dindex - 1) + + (eindex < 0 ? 0 : Math.max(0, -parseInt(str.slice(eindex + 1)))) + ); + } +}; - const invalid = Common.validateArg(normalized, null, resolver); - if (invalid) { - ret = schema.$_createError('any.ref', resolved, { arg: key, ref: args[key], reason: invalid }, state, prefs); - break; - } - args[key] = normalized; - } - } +module.exports = Any.extend({ - // Test rule + type: 'number', - ret = ret || definition.validate(value, helpers, args, rule); // Use ret if already set to reference error + flags: { - const result = internals.rule(ret, rule); - if (result.errors) { - state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'error'); + unsafe: { default: false } + }, - if (rule.warn) { - state.mainstay.warnings.push(...result.errors); - continue; + coerce: { + from: 'string', + method(value, { schema, error }) { + + const matches = value.match(internals.numberRx); + if (!matches) { + return; } - if (prefs.abortEarly) { - return internals.finalize(value, result.errors, helpers); + value = value.trim(); + const result = { value: parseFloat(value) }; + + if (result.value === 0) { + result.value = 0; // -0 } - errors.push(...result.errors); - } - else { - state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'pass'); - state.mainstay.tracer.value(state, 'rule', value, result.value, rule.name); - value = result.value; + if (!schema._flags.unsafe) { + if (value.match(/e/i)) { + if (internals.extractSignificantDigits(value) !== internals.extractSignificantDigits(String(result.value))) { + result.errors = error('number.unsafe'); + return result; + } + } + else { + const string = result.value.toString(); + if (string.match(/e/i)) { + return result; + } + + if (string !== internals.normalizeDecimal(value)) { + result.errors = error('number.unsafe'); + return result; + } + } + } + + return result; } - } + }, - return internals.finalize(value, errors, helpers); -}; + validate(value, { schema, error, prefs }) { + if (value === Infinity || + value === -Infinity) { -internals.rule = function (ret, rule) { + return { value, errors: error('number.infinity') }; + } - if (ret instanceof Errors.Report) { - internals.error(ret, rule); - return { errors: [ret], value: null }; - } + if (!Common.isNumber(value)) { + return { value, errors: error('number.base') }; + } - if (Array.isArray(ret) && - ret[Common.symbols.errors]) { + const result = { value }; - ret.forEach((report) => internals.error(report, rule)); - return { errors: ret, value: null }; - } + if (prefs.convert) { + const rule = schema.$_getRule('precision'); + if (rule) { + const precision = Math.pow(10, rule.args.limit); // This is conceptually equivalent to using toFixed but it should be much faster + result.value = Math.round(result.value * precision) / precision; + } + } - return { errors: null, value: ret }; -}; + if (result.value === 0) { + result.value = 0; // -0 + } + if (!schema._flags.unsafe && + (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)) { -internals.error = function (report, rule) { + result.errors = error('number.unsafe'); + } - if (rule.message) { - report._setTemplate(rule.message); - } + return result; + }, - return report; -}; + rules: { + compare: { + method: false, + validate(value, helpers, { limit }, { name, operator, args }) { -internals.finalize = function (value, errors, helpers) { + if (Common.compare(value, limit, operator)) { + return value; + } - errors = errors || []; - const { schema, state, prefs } = helpers; + return helpers.error('number.' + name, { limit: args.limit, value }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.isNumber, + message: 'must be a number' + } + ] + }, - // Failover value + greater: { + method(limit) { - if (errors.length) { - const failover = internals.default('failover', undefined, errors, helpers); - if (failover !== undefined) { - state.mainstay.tracer.value(state, 'failover', value, failover); - value = failover; - errors = []; - } - } + return this.$_addRule({ name: 'greater', method: 'compare', args: { limit }, operator: '>' }); + } + }, - // Error override + integer: { + method() { - if (errors.length && - schema._flags.error) { + return this.$_addRule('integer'); + }, + validate(value, helpers) { - if (typeof schema._flags.error === 'function') { - errors = schema._flags.error(errors); - if (!Array.isArray(errors)) { - errors = [errors]; + if (Math.trunc(value) - value === 0) { + return value; + } + + return helpers.error('number.integer'); } + }, - for (const error of errors) { - Assert(error instanceof Error || error instanceof Errors.Report, 'error() must return an Error object'); + less: { + method(limit) { + + return this.$_addRule({ name: 'less', method: 'compare', args: { limit }, operator: '<' }); } - } - else { - errors = [schema._flags.error]; - } - } + }, - // Default + max: { + method(limit) { - if (value === undefined) { - const defaulted = internals.default('default', value, errors, helpers); - state.mainstay.tracer.value(state, 'default', value, defaulted); - value = defaulted; - } + return this.$_addRule({ name: 'max', method: 'compare', args: { limit }, operator: '<=' }); + } + }, - // Cast + min: { + method(limit) { - if (schema._flags.cast && - value !== undefined) { + return this.$_addRule({ name: 'min', method: 'compare', args: { limit }, operator: '>=' }); + } + }, - const caster = schema._definition.cast[schema._flags.cast]; - if (caster.from(value)) { - const casted = caster.to(value, helpers); - state.mainstay.tracer.value(state, 'cast', value, casted, schema._flags.cast); - value = casted; - } - } + multiple: { + method(base) { - // Externals + const baseDecimalPlace = typeof base === 'number' ? internals.decimalPlaces(base) : null; + const pfactor = Math.pow(10, baseDecimalPlace); - if (schema.$_terms.externals && - prefs.externals && - prefs._externals !== false) { // Disabled for matching + return this.$_addRule({ + name: 'multiple', + args: { + base, + baseDecimalPlace, + pfactor + } + }); + }, + validate(value, helpers, { base, baseDecimalPlace, pfactor }, options) { - for (const { method } of schema.$_terms.externals) { - state.mainstay.externals.push({ method, schema, state, label: Errors.label(schema._flags, state, prefs) }); - } - } + const valueDecimalPlace = internals.decimalPlaces(value); - // Result + if (valueDecimalPlace > baseDecimalPlace) { + // Value with higher precision than base can never be a multiple + return helpers.error('number.multiple', { multiple: options.args.base, value }); + } - const result = { value, errors: errors.length ? errors : null }; + return Math.round(pfactor * value) % Math.round(pfactor * base) === 0 ? + value : + helpers.error('number.multiple', { multiple: options.args.base, value }); + }, + args: [ + { + name: 'base', + ref: true, + assert: (value) => typeof value === 'number' && isFinite(value) && value > 0, + message: 'must be a positive number' + }, + 'baseDecimalPlace', + 'pfactor' + ], + multi: true + }, - if (schema._flags.result) { - result.value = schema._flags.result === 'strip' ? undefined : /* raw */ helpers.original; - state.mainstay.tracer.value(state, schema._flags.result, value, result.value); - state.shadow(value, schema._flags.result); - } + negative: { + method() { - // Cache + return this.sign('negative'); + } + }, - if (schema._cache && - prefs.cache !== false && - !schema._refs.length) { + port: { + method() { - schema._cache.set(helpers.original, result); - } + return this.$_addRule('port'); + }, + validate(value, helpers) { - // Artifacts + if (Number.isSafeInteger(value) && + value >= 0 && + value <= 65535) { - if (value !== undefined && - !result.errors && - schema._flags.artifact !== undefined) { + return value; + } - state.mainstay.artifacts = state.mainstay.artifacts || new Map(); - if (!state.mainstay.artifacts.has(schema._flags.artifact)) { - state.mainstay.artifacts.set(schema._flags.artifact, []); - } + return helpers.error('number.port'); + } + }, - state.mainstay.artifacts.get(schema._flags.artifact).push(state.path); - } + positive: { + method() { - return result; -}; + return this.sign('positive'); + } + }, + precision: { + method(limit) { -internals.prefs = function (schema, prefs) { + Assert(Number.isSafeInteger(limit), 'limit must be an integer'); - const isDefaultOptions = prefs === Common.defaults; - if (isDefaultOptions && - schema._preferences[Common.symbols.prefs]) { + return this.$_addRule({ name: 'precision', args: { limit } }); + }, + validate(value, helpers, { limit }) { - return schema._preferences[Common.symbols.prefs]; - } + const places = value.toString().match(internals.precisionRx); + const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0); + if (decimals <= limit) { + return value; + } - prefs = Common.preferences(prefs, schema._preferences); - if (isDefaultOptions) { - schema._preferences[Common.symbols.prefs] = prefs; - } + return helpers.error('number.precision', { limit, value }); + }, + convert: true + }, - return prefs; -}; + sign: { + method(sign) { + Assert(['negative', 'positive'].includes(sign), 'Invalid sign', sign); -internals.default = function (flag, value, errors, helpers) { + return this.$_addRule({ name: 'sign', args: { sign } }); + }, + validate(value, helpers, { sign }) { - const { schema, state, prefs } = helpers; - const source = schema._flags[flag]; - if (prefs.noDefaults || - source === undefined) { + if (sign === 'negative' && value < 0 || + sign === 'positive' && value > 0) { - return value; - } + return value; + } - state.mainstay.tracer.log(schema, state, 'rule', flag, 'full'); + return helpers.error(`number.${sign}`); + } + }, - if (!source) { - return source; - } + unsafe: { + method(enabled = true) { - if (typeof source === 'function') { - const args = source.length ? [Clone(state.ancestors[0]), helpers] : []; + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - try { - return source(...args); - } - catch (err) { - errors.push(schema.$_createError(`any.${flag}`, null, { error: err }, state, prefs)); - return; + return this.$_setFlag('unsafe', enabled); + } } - } + }, - if (typeof source !== 'object') { - return source; - } + cast: { + string: { + from: (value) => typeof value === 'number', + to(value, helpers) { - if (source[Common.symbols.literal]) { - return source.literal; - } + return value.toString(); + } + } + }, - if (Common.isResolvable(source)) { - return source.resolve(value, state, prefs); + messages: { + 'number.base': '{{#label}} must be a number', + 'number.greater': '{{#label}} must be greater than {{#limit}}', + 'number.infinity': '{{#label}} cannot be infinity', + 'number.integer': '{{#label}} must be an integer', + 'number.less': '{{#label}} must be less than {{#limit}}', + 'number.max': '{{#label}} must be less than or equal to {{#limit}}', + 'number.min': '{{#label}} must be greater than or equal to {{#limit}}', + 'number.multiple': '{{#label}} must be a multiple of {{#multiple}}', + 'number.negative': '{{#label}} must be a negative number', + 'number.port': '{{#label}} must be a valid port', + 'number.positive': '{{#label}} must be a positive number', + 'number.precision': '{{#label}} must have no more than {{#limit}} decimal places', + 'number.unsafe': '{{#label}} must be a safe number' } - - return Clone(source); -}; +}); -internals.trim = function (value, schema) { +// Helpers - if (typeof value !== 'string') { - return value; - } +internals.extractSignificantDigits = function (value) { - const trim = schema.$_getRule('trim'); - if (!trim || - !trim.args.enabled) { + return value + .replace(internals.exponentialPartRegex, '') + .replace(internals.dotRegex, '') + .replace(internals.trailingZerosRegex, '') + .replace(internals.leadingSignAndZerosRegex, ''); +}; - return value; - } - return value.trim(); -}; +internals.normalizeDecimal = function (str) { + str = str + // Remove leading plus signs + .replace(/^\+/, '') + // Remove trailing zeros if there is a decimal point and unecessary decimal points + .replace(/\.0*$/, '') + // Add a integer 0 if the numbers starts with a decimal point + .replace(/^(-?)\.([^\.]*)$/, '$10.$2') + // Remove leading zeros + .replace(/^(-?)0+([0-9])/, '$1$2'); -internals.ignore = { - active: false, - debug: Ignore, - entry: Ignore, - filter: Ignore, - log: Ignore, - resolve: Ignore, - value: Ignore -}; + if (str.includes('.') && + str.endsWith('0')) { + str = str.replace(/0+$/, ''); + } -internals.errorsArray = function () { + if (str === '-0') { + return '0'; + } - const errors = []; - errors[Common.symbols.errors] = true; - return errors; + return str; }; /***/ }), -/***/ 71944: +/***/ 46878: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Assert = __nccwpck_require__(32718); -const DeepEqual = __nccwpck_require__(55801); - -const Common = __nccwpck_require__(72448); +const Keys = __nccwpck_require__(79130); const internals = {}; -module.exports = internals.Values = class { - - constructor(values, refs) { - - this._values = new Set(values); - this._refs = new Set(refs); - this._lowercase = internals.lowercases(values); - - this._override = false; - } - - get length() { - - return this._values.size + this._refs.size; - } - - add(value, refs) { - - // Reference - - if (Common.isResolvable(value)) { - if (!this._refs.has(value)) { - this._refs.add(value); - - if (refs) { // Skipped in a merge - refs.register(value); - } - } - - return; - } +module.exports = Keys.extend({ - // Value + type: 'object', - if (!this.has(value, null, null, false)) { - this._values.add(value); + cast: { + map: { + from: (value) => value && typeof value === 'object', + to(value, helpers) { - if (typeof value === 'string') { - this._lowercase.set(value.toLowerCase(), value); + return new Map(Object.entries(value)); } } } +}); - static merge(target, source, remove) { - target = target || new internals.Values(); +/***/ }), - if (source) { - if (source._override) { - return source.clone(); - } +/***/ 72260: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (const item of [...source._values, ...source._refs]) { - target.add(item); - } - } +"use strict"; - if (remove) { - for (const item of [...remove._values, ...remove._refs]) { - target.remove(item); - } - } - return target.length ? target : null; - } +const Assert = __nccwpck_require__(32718); +const Domain = __nccwpck_require__(97425); +const Email = __nccwpck_require__(3283); +const Ip = __nccwpck_require__(82337); +const EscapeRegex = __nccwpck_require__(91965); +const Tlds = __nccwpck_require__(53092); +const Uri = __nccwpck_require__(74983); - remove(value) { +const Any = __nccwpck_require__(9512); +const Common = __nccwpck_require__(72448); - // Reference - if (Common.isResolvable(value)) { - this._refs.delete(value); - return; +const internals = { + tlds: Tlds instanceof Set ? { tlds: { allow: Tlds, deny: null } } : false, // $lab:coverage:ignore$ + base64Regex: { + // paddingRequired + true: { + // urlSafe + true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}==|[\w\-]{3}=)?$/, + false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ + }, + false: { + true: /^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}(==)?|[\w\-]{3}=?)?$/, + false: /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/ } + }, + dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/, + hexRegex: { + withPrefix: /^0x[0-9a-f]+$/i, + withOptionalPrefix: /^(?:0x)?[0-9a-f]+$/i, + withoutPrefix: /^[0-9a-f]+$/i + }, + ipRegex: Ip.regex({ cidr: 'forbidden' }).regex, + isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/, - // Value - - this._values.delete(value); + guidBrackets: { + '{': '}', '[': ']', '(': ')', '': '' + }, + guidVersions: { + uuidv1: '1', + uuidv2: '2', + uuidv3: '3', + uuidv4: '4', + uuidv5: '5', + uuidv6: '6', + uuidv7: '7', + uuidv8: '8' + }, + guidSeparators: new Set([undefined, true, false, '-', ':']), - if (typeof value === 'string') { - this._lowercase.delete(value.toLowerCase()); - } - } + normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD'] +}; - has(value, state, prefs, insensitive) { - return !!this.get(value, state, prefs, insensitive); - } +module.exports = Any.extend({ - get(value, state, prefs, insensitive) { + type: 'string', - if (!this.length) { - return false; - } + flags: { - // Simple match + insensitive: { default: false }, + truncate: { default: false } + }, - if (this._values.has(value)) { - return { value }; - } + terms: { - // Case insensitive string match + replacements: { init: null } + }, - if (typeof value === 'string' && - value && - insensitive) { + coerce: { + from: 'string', + method(value, { schema, state, prefs }) { - const found = this._lowercase.get(value.toLowerCase()); - if (found) { - return { value: found }; + const normalize = schema.$_getRule('normalize'); + if (normalize) { + value = value.normalize(normalize.args.form); } - } - if (!this._refs.size && - typeof value !== 'object') { - - return false; - } + const casing = schema.$_getRule('case'); + if (casing) { + value = casing.args.direction === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase(); + } - // Objects + const trim = schema.$_getRule('trim'); + if (trim && + trim.args.enabled) { - if (typeof value === 'object') { - for (const item of this._values) { - if (DeepEqual(item, value)) { - return { value: item }; - } + value = value.trim(); } - } - // References - - if (state) { - for (const ref of this._refs) { - const resolved = ref.resolve(value, state, prefs, null, { in: true }); - if (resolved === undefined) { - continue; + if (schema.$_terms.replacements) { + for (const replacement of schema.$_terms.replacements) { + value = value.replace(replacement.pattern, replacement.replacement); } + } - const items = !ref.in || typeof resolved !== 'object' - ? [resolved] - : Array.isArray(resolved) ? resolved : Object.keys(resolved); - - for (const item of items) { - if (typeof item !== typeof value) { - continue; - } + const hex = schema.$_getRule('hex'); + if (hex && + hex.args.options.byteAligned && + value.length % 2 !== 0) { - if (insensitive && - value && - typeof value === 'string') { + value = `0${value}`; + } - if (item.toLowerCase() === value.toLowerCase()) { - return { value: item, ref }; - } - } - else { - if (DeepEqual(item, value)) { - return { value: item, ref }; - } - } + if (schema.$_getRule('isoDate')) { + const iso = internals.isoDate(value); + if (iso) { + value = iso; } } - } - - return false; - } - - override() { - - this._override = true; - } - - values(options) { - if (options && - options.display) { - - const values = []; + if (schema._flags.truncate) { + const rule = schema.$_getRule('max'); + if (rule) { + let limit = rule.args.limit; + if (Common.isResolvable(limit)) { + limit = limit.resolve(value, state, prefs); + if (!Common.limit(limit)) { + return { value, errors: schema.$_createError('any.ref', limit, { ref: rule.args.limit, arg: 'limit', reason: 'must be a positive integer' }, state, prefs) }; + } + } - for (const item of [...this._values, ...this._refs]) { - if (item !== undefined) { - values.push(item); + value = value.slice(0, limit); } } - return values; + return { value }; } + }, - return Array.from([...this._values, ...this._refs]); - } - - clone() { - - const set = new internals.Values(this._values, this._refs); - set._override = this._override; - return set; - } + validate(value, { schema, error }) { - concat(source) { + if (typeof value !== 'string') { + return { value, errors: error('string.base') }; + } - Assert(!source._override, 'Cannot concat override set of values'); + if (value === '') { + const min = schema.$_getRule('min'); + if (min && + min.args.limit === 0) { - const set = new internals.Values([...this._values, ...source._values], [...this._refs, ...source._refs]); - set._override = this._override; - return set; - } + return; + } - describe() { + return { value, errors: error('string.empty') }; + } + }, - const normalized = []; + rules: { - if (this._override) { - normalized.push({ override: true }); - } + alphanum: { + method() { - for (const value of this._values.values()) { - normalized.push(value && typeof value === 'object' ? { value } : value); - } + return this.$_addRule('alphanum'); + }, + validate(value, helpers) { - for (const value of this._refs.values()) { - normalized.push(value.describe()); - } + if (/^[a-zA-Z0-9]+$/.test(value)) { + return value; + } - return normalized; - } -}; + return helpers.error('string.alphanum'); + } + }, + base64: { + method(options = {}) { -internals.Values.prototype[Common.symbols.values] = true; + Common.assertOptions(options, ['paddingRequired', 'urlSafe']); + options = { urlSafe: false, paddingRequired: true, ...options }; + Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); + Assert(typeof options.urlSafe === 'boolean', 'urlSafe must be boolean'); -// Aliases + return this.$_addRule({ name: 'base64', args: { options } }); + }, + validate(value, helpers, { options }) { -internals.Values.prototype.slice = internals.Values.prototype.clone; + const regex = internals.base64Regex[options.paddingRequired][options.urlSafe]; + if (regex.test(value)) { + return value; + } + return helpers.error('string.base64'); + } + }, -// Helpers + case: { + method(direction) { -internals.lowercases = function (from) { + Assert(['lower', 'upper'].includes(direction), 'Invalid case:', direction); - const map = new Map(); + return this.$_addRule({ name: 'case', args: { direction } }); + }, + validate(value, helpers, { direction }) { - if (from) { - for (const value of from) { - if (typeof value === 'string') { - map.set(value.toLowerCase(), value); - } - } - } + if (direction === 'lower' && value === value.toLocaleLowerCase() || + direction === 'upper' && value === value.toLocaleUpperCase()) { - return map; -}; + return value; + } + return helpers.error(`string.${direction}case`); + }, + convert: true + }, -/***/ }), + creditCard: { + method() { -/***/ 90250: -/***/ (function(module, exports, __nccwpck_require__) { + return this.$_addRule('creditCard'); + }, + validate(value, helpers) { -/* 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() { + let i = value.length; + let sum = 0; + let mul = 1; - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; + while (i--) { + const char = value.charAt(i) * mul; + sum = sum + (char - (char > 9) * 9); + mul = mul ^ 3; + } - /** Used as the semantic version number. */ - var VERSION = '4.17.21'; + if (sum > 0 && + sum % 10 === 0) { - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; + return value; + } - /** 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`'; + return helpers.error('string.creditCard'); + } + }, - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; + dataUri: { + method(options = {}) { - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; + Common.assertOptions(options, ['paddingRequired']); - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; + options = { paddingRequired: true, ...options }; + Assert(typeof options.paddingRequired === 'boolean', 'paddingRequired must be boolean'); - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; + return this.$_addRule({ name: 'dataUri', args: { options } }); + }, + validate(value, helpers, { options }) { - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; + const matches = value.match(internals.dataUriRegex); - /** 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; + if (matches) { + if (!matches[2]) { + return value; + } - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; + if (matches[2] !== 'base64') { + return value; + } - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; + const base64regex = internals.base64Regex[options.paddingRequired].false; + if (base64regex.test(matches[3])) { + return value; + } + } - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; + return helpers.error('string.dataUri'); + } + }, - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + domain: { + method(options) { - /** 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; + if (options) { + Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); + } - /** 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] - ]; + const address = internals.addressOptions(options); + return this.$_addRule({ name: 'domain', args: { options }, address }); + }, + validate(value, helpers, args, { address }) { - /** `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]'; + if (Domain.isValid(value, address)) { + return 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]'; + return helpers.error('string.domain'); + } + }, - /** 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; + email: { + method(options = {}) { - /** 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); + Common.assertOptions(options, ['allowFullyQualified', 'allowUnicode', 'ignoreLength', 'maxDomainSegments', 'minDomainSegments', 'multiple', 'separator', 'tlds']); + Assert(options.multiple === undefined || typeof options.multiple === 'boolean', 'multiple option must be an boolean'); - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; + const address = internals.addressOptions(options); + const regex = new RegExp(`\\s*[${options.separator ? EscapeRegex(options.separator) : ','}]\\s*`); - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + return this.$_addRule({ name: 'email', args: { options }, regex, address }); + }, + validate(value, helpers, { options }, { regex, address }) { - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); + const emails = options.multiple ? value.split(regex) : [value]; + const invalids = []; + for (const email of emails) { + if (!Email.isValid(email, address)) { + invalids.push(email); + } + } - /** Used to match leading whitespace. */ - var reTrimStart = /^\s+/; + if (!invalids.length) { + return value; + } - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; + return helpers.error('string.email', { value, invalids }); + } + }, - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; + guid: { + alias: 'uuid', + method(options = {}) { - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + Common.assertOptions(options, ['version', 'separator']); - /** - * 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]/; + let versionNumbers = ''; - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; + if (options.version) { + const versions = [].concat(options.version); - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + Assert(versions.length >= 1, 'version must have at least 1 valid version specified'); + const set = new Set(); - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; + for (let i = 0; i < versions.length; ++i) { + const version = versions[i]; + Assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); + const versionNumber = internals.guidVersions[version.toLowerCase()]; + Assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', ')); + Assert(!set.has(versionNumber), 'version at position ' + i + ' must not be a duplicate'); - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + versionNumbers += versionNumber; + set.add(versionNumber); + } + } - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; + Assert(internals.guidSeparators.has(options.separator), 'separator must be one of true, false, "-", or ":"'); + const separator = options.separator === undefined ? '[:-]?' : + options.separator === true ? '[:-]' : + options.separator === false ? '[]?' : `\\${options.separator}`; - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; + const regex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}(${separator})[0-9A-F]{4}\\2?[${versionNumbers || '0-9A-F'}][0-9A-F]{3}\\2?[${versionNumbers ? '89AB' : '0-9A-F'}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`, 'i'); - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; + return this.$_addRule({ name: 'guid', args: { options }, regex }); + }, + validate(value, helpers, args, { regex }) { - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; + const results = regex.exec(value); - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + if (!results) { + return helpers.error('string.guid'); + } - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; + // Matching braces - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + if (internals.guidBrackets[results[1]] !== results[results.length - 1]) { + return helpers.error('string.guid'); + } - /** 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; + return value; + } + }, - /** 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'; + hex: { + method(options = {}) { - /** 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('|') + ')'; + Common.assertOptions(options, ['byteAligned', 'prefix']); - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); + options = { byteAligned: false, prefix: false, ...options }; + Assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean'); + Assert(typeof options.prefix === 'boolean' || options.prefix === 'optional', 'prefix must be boolean or "optional"'); - /** - * 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 this.$_addRule({ name: 'hex', args: { options } }); + }, + validate(value, helpers, { options }) { - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + const re = options.prefix === 'optional' ? + internals.hexRegex.withOptionalPrefix : + options.prefix === true ? + internals.hexRegex.withPrefix : + internals.hexRegex.withoutPrefix; + if (!re.test(value)) { + return helpers.error('string.hex'); + } - /** 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'); + if (options.byteAligned && + value.length % 2 !== 0) { - /** 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 + ']'); + return helpers.error('string.hexAlign'); + } - /** 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 ]/; + return value; + } + }, - /** 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' - ]; + hostname: { + method() { - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; + return this.$_addRule('hostname'); + }, + validate(value, helpers) { - /** 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; + if (Domain.isValid(value, { minDomainSegments: 1 }) || + internals.ipRegex.test(value)) { - /** 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; + return value; + } - /** 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' - }; + return helpers.error('string.hostname'); + } + }, - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; + insensitive: { + method() { - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; + return this.$_setFlag('insensitive', true); + } + }, - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; + ip: { + method(options = {}) { - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; + Common.assertOptions(options, ['cidr', 'version']); - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + const { cidr, versions, regex } = Ip.regex(options); + const version = options.version ? versions : undefined; + return this.$_addRule({ name: 'ip', args: { options: { cidr, version } }, regex }); + }, + validate(value, helpers, { options }, { regex }) { - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + if (regex.test(value)) { + return value; + } - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); + if (options.version) { + return helpers.error('string.ipVersion', { value, cidr: options.cidr, version: options.version }); + } - /** Detect free variable `exports`. */ - var freeExports = true && exports && !exports.nodeType && exports; + return helpers.error('string.ip', { value, cidr: options.cidr }); + } + }, - /** Detect free variable `module`. */ - var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; + isoDate: { + method() { - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + return this.$_addRule('isoDate'); + }, + validate(value, { error }) { - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; + if (internals.isoDate(value)) { + return value; + } - /** 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 error('string.isoDate'); + } + }, - if (types) { - return types; - } + isoDuration: { + method() { - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); + return this.$_addRule('isoDuration'); + }, + validate(value, helpers) { - /* 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 (internals.isoDurationRegex.test(value)) { + return value; + } - /*--------------------------------------------------------------------------*/ + return helpers.error('string.isoDuration'); + } + }, - /** - * 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); - } + length: { + method(limit, encoding) { - /** - * 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; + return internals.length(this, 'length', limit, '=', encoding); + }, + validate(value, helpers, { limit, encoding }, { name, operator, args }) { - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } + const length = encoding ? Buffer && Buffer.byteLength(value, encoding) : value.length; // $lab:coverage:ignore$ + if (Common.compare(length, limit, operator)) { + return value; + } - /** - * 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; + return helpers.error('string.' + name, { limit: args.limit, value, encoding }); + }, + args: [ + { + name: 'limit', + ref: true, + assert: Common.limit, + message: 'must be a positive integer' + }, + 'encoding' + ] + }, - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } + lowercase: { + method() { - /** - * 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; + return this.case('lower'); + } + }, - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } + max: { + method(limit, encoding) { - /** - * 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 internals.length(this, 'max', limit, '<=', encoding); + }, + args: ['limit', 'encoding'] + }, - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } + min: { + method(limit, encoding) { - /** - * 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 = []; + return internals.length(this, 'min', limit, '>=', encoding); + }, + args: ['limit', 'encoding'] + }, - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } + normalize: { + method(form = 'NFC') { - /** - * 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; - } + Assert(internals.normalizationForms.includes(form), 'normalization form must be one of ' + internals.normalizationForms.join(', ')); - /** - * 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; + return this.$_addRule({ name: 'normalize', args: { form } }); + }, + validate(value, { error }, { form }) { - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } + if (value === value.normalize(form)) { + return value; + } - /** - * 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 error('string.normalize', { value, form }); + }, + convert: true + }, - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } + pattern: { + alias: 'regex', + method(regex, options = {}) { - /** - * 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; + Assert(regex instanceof RegExp, 'regex must be a RegExp'); + Assert(!regex.flags.includes('g') && !regex.flags.includes('y'), 'regex should not use global or sticky mode'); - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } + if (typeof options === 'string') { + options = { name: options }; + } - /** - * 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; + Common.assertOptions(options, ['invert', 'name']); - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } + const errorCode = ['string.pattern', options.invert ? '.invert' : '', options.name ? '.name' : '.base'].join(''); + return this.$_addRule({ name: 'pattern', args: { regex, options }, errorCode }); + }, + validate(value, helpers, { regex, options }, { errorCode }) { - /** - * 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; - } + const patternMatch = regex.test(value); - /** - * 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; + if (patternMatch ^ options.invert) { + return value; + } - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } + return helpers.error(errorCode, { name: options.name, regex, value }); + }, + args: ['regex', 'options'], + multi: true + }, - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); + replace: { + method(pattern, replacement) { - /** - * 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(''); - } + if (typeof pattern === 'string') { + pattern = new RegExp(EscapeRegex(pattern), 'g'); + } - /** - * 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) || []; - } + Assert(pattern instanceof RegExp, 'pattern must be a RegExp'); + Assert(typeof replacement === 'string', 'replacement must be a String'); - /** - * 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; - } - }); - return result; - } + const obj = this.clone(); - /** - * 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); + if (!obj.$_terms.replacements) { + obj.$_terms.replacements = []; + } + + obj.$_terms.replacements.push({ pattern, replacement }); + return obj; + } + }, + + token: { + method() { + + return this.$_addRule('token'); + }, + validate(value, helpers) { - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } + if (/^\w+$/.test(value)) { + return value; + } - /** - * 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); - } + return helpers.error('string.token'); + } + }, - /** - * 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; + trim: { + method(enabled = true) { - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - /** - * 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; - } + return this.$_addRule({ name: 'trim', args: { enabled } }); + }, + validate(value, helpers, { enabled }) { - /** - * 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 (!enabled || + value === value.trim()) { - /** - * 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]; - }; - } + return value; + } - /** - * 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]; - }; - } + return helpers.error('string.trim'); + }, + convert: true + }, - /** - * 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; - } + truncate: { + method(enabled = true) { - /** - * 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; + Assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } + return this.$_setFlag('truncate', enabled); + } + }, - /** - * 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; + uppercase: { + method() { - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; - } + return this.case('upper'); + } + }, - /** - * 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); + uri: { + method(options = {}) { - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } + Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme', 'encodeUri']); - /** - * 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.domain) { + Common.assertOptions(options.domain, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']); + } - /** - * 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; - } + const { regex, scheme } = Uri.regex(options); + const domain = options.domain ? internals.addressOptions(options.domain) : null; + return this.$_addRule({ name: 'uri', args: { options }, regex, domain, scheme }); + }, + validate(value, helpers, { options }, { regex, domain, scheme }) { - /** - * 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); - }; - } + if (['http:/', 'https:/'].includes(value)) { // scheme:/ is technically valid but makes no sense + return helpers.error('string.uri'); + } - /** - * 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]; - }); - } + let match = regex.exec(value); - /** - * 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 (!match && helpers.prefs.convert && options.encodeUri) { + const encoded = encodeURI(value); + match = regex.exec(encoded); + if (match) { + value = encoded; + } + } - /** - * 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; + if (match) { + const matched = match[1] || match[2]; + if (domain && + (!options.allowRelative || matched) && + !Domain.isValid(matched, domain)) { - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } + return helpers.error('string.domain', { value: matched }); + } - /** - * 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; + return value; + } - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } + if (options.relativeOnly) { + return helpers.error('string.uriRelativeOnly'); + } - /** - * 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; + if (options.scheme) { + return helpers.error('string.uriCustomScheme', { scheme, value }); + } - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } + return helpers.error('string.uri'); + } + } + }, - /** - * 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); + manifest: { - /** - * 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); + build(obj, desc) { - /** - * 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]; - } + if (desc.replacements) { + for (const { pattern, replacement } of desc.replacements) { + obj = obj.replace(pattern, replacement); + } + } - /** - * 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]; - } + return obj; + } + }, - /** - * 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); - } + messages: { + 'string.alphanum': '{{#label}} must only contain alpha-numeric characters', + 'string.base': '{{#label}} must be a string', + 'string.base64': '{{#label}} must be a valid base64 string', + 'string.creditCard': '{{#label}} must be a credit card', + 'string.dataUri': '{{#label}} must be a valid dataUri string', + 'string.domain': '{{#label}} must contain a valid domain name', + 'string.email': '{{#label}} must be a valid email', + 'string.empty': '{{#label}} is not allowed to be empty', + 'string.guid': '{{#label}} must be a valid GUID', + 'string.hex': '{{#label}} must only contain hexadecimal characters', + 'string.hexAlign': '{{#label}} hex decoded representation must be byte aligned', + 'string.hostname': '{{#label}} must be a valid hostname', + 'string.ip': '{{#label}} must be a valid ip address with a {{#cidr}} CIDR', + 'string.ipVersion': '{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR', + 'string.isoDate': '{{#label}} must be in iso format', + 'string.isoDuration': '{{#label}} must be a valid ISO 8601 duration', + 'string.length': '{{#label}} length must be {{#limit}} characters long', + 'string.lowercase': '{{#label}} must only contain lowercase characters', + 'string.max': '{{#label}} length must be less than or equal to {{#limit}} characters long', + 'string.min': '{{#label}} length must be at least {{#limit}} characters long', + 'string.normalize': '{{#label}} must be unicode normalized in the {{#form}} form', + 'string.token': '{{#label}} must only contain alpha-numeric and underscore characters', + 'string.pattern.base': '{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}', + 'string.pattern.name': '{{#label}} with value {:[.]} fails to match the {{#name}} pattern', + 'string.pattern.invert.base': '{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}', + 'string.pattern.invert.name': '{{#label}} with value {:[.]} matches the inverted {{#name}} pattern', + 'string.trim': '{{#label}} must not have leading or trailing whitespace', + 'string.uri': '{{#label}} must be a valid uri', + 'string.uriCustomScheme': '{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern', + 'string.uriRelativeOnly': '{{#label}} must be a valid relative uri', + 'string.uppercase': '{{#label}} must only contain uppercase characters' + } +}); - /** - * 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); - } - /** - * 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 = []; +// Helpers - while (!(data = iterator.next()).done) { - result.push(data.value); +internals.addressOptions = function (options) { + + if (!options) { + return internals.tlds || options; // $lab:coverage:ignore$ } - 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); + // minDomainSegments - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } + Assert(options.minDomainSegments === undefined || + Number.isSafeInteger(options.minDomainSegments) && options.minDomainSegments > 0, 'minDomainSegments must be a positive integer'); - /** - * 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)); - }; - } + // maxDomainSegments - /** - * 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 = []; + Assert(options.maxDomainSegments === undefined || + Number.isSafeInteger(options.maxDomainSegments) && options.maxDomainSegments > 0, 'maxDomainSegments must be a positive integer'); + + // tlds - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } + if (options.tlds === false) { + return options; } - 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); + if (options.tlds === true || + options.tlds === undefined) { - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } + Assert(internals.tlds, 'Built-in TLD list disabled'); + return Object.assign({}, options, internals.tlds); + } - /** - * 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); + Assert(typeof options.tlds === 'object', 'tlds must be true, false, or an object'); - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } + const deny = options.tlds.deny; + if (deny) { + if (Array.isArray(deny)) { + options = Object.assign({}, options, { tlds: { deny: new Set(deny) } }); + } - /** - * 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; + Assert(options.tlds.deny instanceof Set, 'tlds.deny must be an array, Set, or boolean'); + Assert(!options.tlds.allow, 'Cannot specify both tlds.allow and tlds.deny lists'); + internals.validateTlds(options.tlds.deny, 'tlds.deny'); + return options; + } - while (++index < length) { - if (array[index] === value) { - return index; - } + const allow = options.tlds.allow; + if (!allow) { + return options; } - 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 (allow === true) { + Assert(internals.tlds, 'Built-in TLD list disabled'); + return Object.assign({}, options, internals.tlds); } - 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 (Array.isArray(allow)) { + options = Object.assign({}, options, { tlds: { allow: new Set(allow) } }); + } - /** - * 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); - } + Assert(options.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean'); + internals.validateTlds(options.tlds.allow, 'tlds.allow'); + return options; +}; - /** - * 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; - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index; - } +internals.validateTlds = function (set, source) { - /** - * 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); + for (const tld of set) { + Assert(Domain.isValid(tld, { minDomainSegments: 1, maxDomainSegments: 1 }), `${source} must contain valid top level domain names`); + } +}; - /** - * 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; + +internals.isoDate = function (value) { + + if (!Common.isIsoDate(value)) { + return null; } - 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 (/.*T.*[+-]\d\d$/.test(value)) { // Add missing trailing zeros to timeshift + value += '00'; + } - /** - * 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) || []; - } + const date = new Date(value); + if (isNaN(date.getTime())) { + return null; + } - /*--------------------------------------------------------------------------*/ + return date.toISOString(); +}; - /** - * 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; +internals.length = function (schema, name, limit, operator, encoding) { - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; + Assert(!encoding || Buffer && Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); // $lab:coverage:ignore$ - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; + return schema.$_addRule({ name, method: 'length', args: { limit, encoding }, operator }); +}; - /** 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; +/***/ 40971: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** 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) : ''; - }()); +"use strict"; - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); +const Assert = __nccwpck_require__(32718); - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; +const Any = __nccwpck_require__(9512); - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - /** 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; +const internals = {}; - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - /** 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; +internals.Map = class extends Map { - /* 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; + slice() { - /* 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'); + return new internals.Map(this); + } +}; - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; - /** Used to lookup unminified function names. */ - var realNames = {}; +module.exports = Any.extend({ - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); + type: 'symbol', - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; + terms: { - /*------------------------------------------------------------------------*/ + map: { init: new internals.Map() } + }, - /** - * 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); - } + coerce: { + method(value, { schema, error }) { - /** - * 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 {}; + const lookup = schema.$_terms.map.get(value); + if (lookup) { + value = lookup; + } + + if (!schema._flags.only || + typeof value === 'symbol') { + + return { value }; + } + + return { value, errors: error('symbol.map', { map: schema.$_terms.map }) }; } - if (objectCreate) { - return objectCreate(proto); + }, + + validate(value, { error }) { + + if (typeof value !== 'symbol') { + return { value, errors: error('symbol.base') }; } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); + }, - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } + rules: { + map: { + method(iterable) { - /** - * 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; - } + if (iterable && + !iterable[Symbol.iterator] && + typeof iterable === 'object') { - /** - * 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 = { + iterable = Object.entries(iterable); + } - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, + Assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object'); - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, + const obj = this.clone(); - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, + const symbols = []; + for (const entry of iterable) { + Assert(entry && entry[Symbol.iterator], 'Entry must be an iterable'); + const [key, value] = entry; - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', + Assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be of type object, function, or Symbol'); + Assert(typeof value === 'symbol', 'Value must be a Symbol'); - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { + obj.$_terms.map.set(key, value); + symbols.push(value); + } - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; + return obj.valid(...symbols); + } + } + }, - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; + manifest: { - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; + build(obj, desc) { - /*------------------------------------------------------------------------*/ + if (desc.map) { + obj = obj.map(desc.map); + } - /** - * 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__ = []; - } + return obj; + } + }, - /** - * 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; + messages: { + 'symbol.base': '{{#label}} must be a symbol', + 'symbol.map': '{{#label}} must be one of {{#map}}' } +}); - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); +/***/ }), - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; +/***/ 91804: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - outer: - while (length-- && resIndex < takeCount) { - index += dir; +"use strict"; - var iterIndex = -1, - value = array[index]; - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); +const Assert = __nccwpck_require__(32718); +const Clone = __nccwpck_require__(85578); +const Ignore = __nccwpck_require__(12887); +const Reach = __nccwpck_require__(18891); - 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; - } +const Common = __nccwpck_require__(72448); +const Errors = __nccwpck_require__(69490); +const State = __nccwpck_require__(73634); - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - /*------------------------------------------------------------------------*/ +const internals = { + result: Symbol('result') +}; - /** - * 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]); - } - } +exports.entry = function (value, schema, prefs) { - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; + let settings = Common.defaults; + if (prefs) { + Assert(prefs.warnings === undefined, 'Cannot override warnings preference in synchronous validation'); + Assert(prefs.artifacts === undefined, 'Cannot override artifacts preference in synchronous validation'); + settings = Common.preferences(Common.defaults, prefs); } - /** - * 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; + const result = internals.entry(value, schema, settings); + Assert(!result.mainstay.externals.length, 'Schema with external rules must use validateAsync()'); + const outcome = { value: result.value }; + + if (result.error) { + outcome.error = result.error; } - /** - * 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; + if (result.mainstay.warnings.length) { + outcome.warning = Errors.details(result.mainstay.warnings); } - /** - * 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); + if (result.mainstay.debug) { + outcome.debug = result.mainstay.debug; } - /** - * 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; + if (result.mainstay.artifacts) { + outcome.artifacts = result.mainstay.artifacts; } - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; + return outcome; +}; - /*------------------------------------------------------------------------*/ - /** - * 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; +exports.entryAsync = async function (value, schema, prefs) { - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } + let settings = Common.defaults; + if (prefs) { + settings = Common.preferences(Common.defaults, prefs); } - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; + const result = internals.entry(value, schema, settings); + const mainstay = result.mainstay; + if (result.error) { + if (mainstay.debug) { + result.error.debug = mainstay.debug; + } + + throw result.error; } - /** - * 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 (mainstay.externals.length) { + let root = result.value; + const errors = []; + for (const external of mainstay.externals) { + const path = external.state.path; + const linked = external.schema.type === 'link' ? mainstay.links.get(external.schema) : null; + let node = root; + let key; + let parent; - 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; - } + const ancestors = path.length ? [root] : []; + const original = path.length ? Reach(value, path) : value; - /** - * 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); + if (path.length) { + key = path[path.length - 1]; - return index < 0 ? undefined : data[index][1]; - } + let current = root; + for (const segment of path.slice(0, -1)) { + current = current[segment]; + ancestors.unshift(current); + } - /** - * 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; - } + parent = ancestors[0]; + node = parent[key]; + } + + try { + const createError = (code, local) => (linked || external.schema).$_createError(code, node, local, external.state, settings); + const output = await external.method(node, { + schema: external.schema, + linked, + state: external.state, + prefs, + original, + error: createError, + errorsArray: internals.errorsArray, + warn: (code, local) => mainstay.warnings.push((linked || external.schema).$_createError(code, node, local, external.state, settings)), + message: (messages, local) => (linked || external.schema).$_createError('external', node, local, external.state, settings, { messages }) + }); + + if (output === undefined || + output === node) { + + continue; + } + + if (output instanceof Errors.Report) { + mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error'); + errors.push(output); + + if (settings.abortEarly) { + break; + } + + continue; + } + + if (Array.isArray(output) && + output[Common.symbols.errors]) { + mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error'); + errors.push(...output); + + if (settings.abortEarly) { + break; + } - /** - * 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); + continue; + } - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } + if (parent) { + mainstay.tracer.value(external.state, 'rule', node, output, 'external'); + parent[key] = output; + } + else { + mainstay.tracer.value(external.state, 'rule', root, output, 'external'); + root = output; + } + } + catch (err) { + if (settings.errors.label) { + err.message += ` (${(external.label)})`; // Change message to include path + } - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; + throw err; + } + } - /*------------------------------------------------------------------------*/ + result.value = root; - /** - * 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; + if (errors.length) { + result.error = Errors.process(errors, value, settings); - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } + if (mainstay.debug) { + result.error.debug = mainstay.debug; + } - /** - * 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 - }; + throw result.error; + } } - /** - * 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; - } + if (!settings.warnings && + !settings.debug && + !settings.artifacts) { - /** - * 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); + return result.value; } - /** - * 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); + const outcome = { value: result.value }; + if (mainstay.warnings.length) { + outcome.warning = Errors.details(mainstay.warnings); } - /** - * 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; + if (mainstay.debug) { + outcome.debug = mainstay.debug; + } - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; + if (mainstay.artifacts) { + outcome.artifacts = mainstay.artifacts; } - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; + return outcome; +}; - /*------------------------------------------------------------------------*/ - /** - * - * 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; +internals.Mainstay = class { - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } + constructor(tracer, debug, links) { - /** - * 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; - } + this.externals = []; + this.warnings = []; + this.tracer = tracer; + this.debug = debug; + this.links = links; + this.shadow = null; + this.artifacts = null; - /** - * 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); + this._snapshots = []; } - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /*------------------------------------------------------------------------*/ - - /** - * 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; - } + snapshot() { - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; + this._snapshots.push({ + externals: this.externals.slice(), + warnings: this.warnings.slice() + }); } - /** - * 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); + restore() { - this.size = data.size; - return result; + const snapshot = this._snapshots.pop(); + this.externals = snapshot.externals; + this.warnings = snapshot.warnings; } - /** - * 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); - } + commit() { - /** - * 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); + this._snapshots.pop(); } +}; - /** - * 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; - } - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; +internals.entry = function (value, schema, prefs) { - /*------------------------------------------------------------------------*/ + // Prepare state - /** - * 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; + const { tracer, cleanup } = internals.tracer(schema, prefs); + const debug = prefs.debug ? [] : null; + const links = schema._ids._schemaChain ? new Map() : null; + const mainstay = new internals.Mainstay(tracer, debug, links); + const schemas = schema._ids._schemaChain ? [{ schema }] : null; + const state = new State([], [], { mainstay, schemas }); - 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; - } + // Validate value - /** - * 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; - } + const result = exports.validate(value, schema, state, prefs); - /** - * 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)); - } + // Process value and errors - /** - * 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)); + if (cleanup) { + schema.$_root.untrace(); } - /** - * 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); - } - } + const error = Errors.process(result.errors, value, prefs); + return { value: result.value, error, mainstay }; +}; - /** - * 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); - } - } - /** - * 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; - } +internals.tracer = function (schema, prefs) { - /** - * 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; + if (schema.$_root._tracer) { + return { tracer: schema.$_root._tracer._register(schema) }; } - /** - * 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); + if (prefs.debug) { + Assert(schema.$_root.trace, 'Debug mode not supported'); + return { tracer: schema.$_root.trace()._register(schema), cleanup: true }; } - /** - * 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); - } + return { tracer: internals.ignore }; +}; - /** - * 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; - } + +exports.validate = function (value, schema, state, prefs, overrides = {}) { + + if (schema.$_terms.whens) { + schema = schema._generate(value, state, prefs).schema; } - /** - * 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; + // Setup state and settings - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; + if (schema._preferences) { + prefs = internals.prefs(schema, prefs); } - /** - * 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; + // Cache + + if (schema._cache && + prefs.cache) { + + const result = schema._cache.get(value); + state.mainstay.tracer.debug(state, 'validate', 'cached', !!result); + if (result) { + return result; } - } - 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; + // Helpers - 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; + const createError = (code, local, localState) => schema.$_createError(code, value, local, localState || state, prefs); + const helpers = { + original: value, + prefs, + schema, + state, + error: createError, + errorsArray: internals.errorsArray, + warn: (code, local, localState) => state.mainstay.warnings.push(createError(code, local, localState)), + message: (messages, local) => schema.$_createError('custom', value, local, state, prefs, { messages }) + }; - 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); + // Prepare + + state.mainstay.tracer.entry(schema, state); + + const def = schema._definition; + if (def.prepare && + value !== undefined && + prefs.convert) { + + const prepared = def.prepare(value, helpers); + if (prepared) { + state.mainstay.tracer.value(state, 'prepare', value, prepared.value); + if (prepared.errors) { + return internals.finalize(prepared.value, [].concat(prepared.errors), helpers); // Prepare error always aborts early + } + + value = prepared.value; } - } - // 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)); - }); - } + // Type coercion - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); + if (def.coerce && + value !== undefined && + prefs.convert && + (!def.coerce.from || def.coerce.from.includes(typeof value))) { - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; + const coerced = def.coerce.method(value, helpers); + if (coerced) { + state.mainstay.tracer.value(state, 'coerced', value, coerced.value); + if (coerced.errors) { + return internals.finalize(coerced.value, [].concat(coerced.errors), helpers); // Coerce error always aborts early + } + + value = coerced.value; } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; } - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; + // Empty value + + const empty = schema._flags.empty; + if (empty && + empty.$_match(internals.trim(value, schema), state.nest(empty), Common.defaults)) { + + state.mainstay.tracer.value(state, 'empty', value, undefined); + value = undefined; } - /** - * 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]; + // Presence requirements (required, optional, forbidden) - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; + const presence = overrides.presence || schema._flags.presence || (schema._flags._endedSwitch ? null : prefs.presence); + if (value === undefined) { + if (presence === 'forbidden') { + return internals.finalize(value, null, helpers); } - } - return true; - } - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); + if (presence === 'required') { + return internals.finalize(value, [schema.$_createError('any.required', value, null, state, prefs)], helpers); + } + + if (presence === 'optional') { + if (schema._flags.default !== Common.symbols.deepDefault) { + return internals.finalize(value, null, helpers); + } + + state.mainstay.tracer.value(state, 'default', value, {}); + value = {}; + } + } + else if (presence === 'forbidden') { + return internals.finalize(value, [schema.$_createError('any.unknown', value, null, state, prefs)], helpers); } - /** - * 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; + // Allowed values - 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); + const errors = []; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; + if (schema._valids) { + const match = schema._valids.get(value, state, prefs, schema._flags.insensitive); + if (match) { + if (prefs.convert) { + state.mainstay.tracer.value(state, 'valids', value, match.value); + value = match.value; } - } - result.push(value); + + state.mainstay.tracer.filter(schema, state, 'valid', match); + return internals.finalize(value, null, helpers); } - else if (!includes(values, computed, comparator)) { - result.push(value); + + if (schema._flags.only) { + const report = schema.$_createError('any.only', value, { valids: schema._valids.values({ display: true }) }, state, prefs); + if (prefs.abortEarly) { + return internals.finalize(value, [report], helpers); + } + + errors.push(report); } - } - return result; } - /** - * 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); + // Denied values - /** - * 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); + if (schema._invalids) { + const match = schema._invalids.get(value, state, prefs, schema._flags.insensitive); + if (match) { + state.mainstay.tracer.filter(schema, state, 'invalid', match); + const report = schema.$_createError('any.invalid', value, { invalids: schema._invalids.values({ display: true }) }, state, prefs); + if (prefs.abortEarly) { + return internals.finalize(value, [report], helpers); + } - /** - * 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; + errors.push(report); + } } - /** - * 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; + // Base type - while (++index < length) { - var value = array[index], - current = iteratee(value); + if (def.validate) { + const base = def.validate(value, helpers); + if (base) { + state.mainstay.tracer.value(state, 'base', value, base.value); + value = base.value; - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; + if (base.errors) { + if (!Array.isArray(base.errors)) { + errors.push(base.errors); + return internals.finalize(value, errors, helpers); // Base error always aborts early + } + + if (base.errors.length) { + errors.push(...base.errors); + return internals.finalize(value, errors, helpers); // Base error always aborts early + } + } } - } - 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; + // Validate tests - 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; + if (!schema._rules.length) { + return internals.finalize(value, errors, helpers); } - /** - * 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 internals.rules(value, errors, helpers); +}; + + +internals.rules = function (value, errors, helpers) { + + const { schema, state, prefs } = helpers; + + for (const rule of schema._rules) { + const definition = schema._definition.rules[rule.method]; + + // Skip rules that are also applied in coerce step + + if (definition.convert && + prefs.convert) { + + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'full'); + continue; } - }); - return result; - } - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; + // Resolve references + + let ret; + let args = rule.args; + if (rule._resolve.length) { + args = Object.assign({}, args); // Shallow copy + for (const key of rule._resolve) { + const resolver = definition.argsByName.get(key); + + const resolved = args[key].resolve(value, state, prefs); + const normalized = resolver.normalize ? resolver.normalize(resolved) : resolved; + + const invalid = Common.validateArg(normalized, null, resolver); + if (invalid) { + ret = schema.$_createError('any.ref', resolved, { arg: key, ref: args[key], reason: invalid }, state, prefs); + break; + } + + args[key] = normalized; + } + } + + // Test rule + + ret = ret || definition.validate(value, helpers, args, rule); // Use ret if already set to reference error + + const result = internals.rule(ret, rule); + if (result.errors) { + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'error'); - predicate || (predicate = isFlattenable); - result || (result = []); + if (rule.warn) { + state.mainstay.warnings.push(...result.errors); + continue; + } - 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; + if (prefs.abortEarly) { + return internals.finalize(value, result.errors, helpers); + } + + errors.push(...result.errors); + } + else { + state.mainstay.tracer.log(schema, state, 'rule', rule.name, 'pass'); + state.mainstay.tracer.value(state, 'rule', value, result.value, rule.name); + value = result.value; } - } - return result; } - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); + return internals.finalize(value, errors, helpers); +}; - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } +internals.rule = function (ret, rule) { - /** - * 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); + if (ret instanceof Errors.Report) { + internals.error(ret, rule); + return { errors: [ret], value: null }; } - /** - * 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]); - }); - } + if (Array.isArray(ret) && + ret[Common.symbols.errors]) { - /** - * 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); + ret.forEach((report) => internals.error(report, rule)); + return { errors: ret, value: null }; + } - var index = 0, - length = path.length; + return { errors: null, value: ret }; +}; - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @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)); - } +internals.error = function (report, rule) { - /** - * 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); + if (rule.message) { + report._setTemplate(rule.message); } - /** - * 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; - } + return report; +}; - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } +internals.finalize = function (value, errors, helpers) { - /** - * 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); - } + errors = errors || []; + const { schema, state, prefs } = helpers; - /** - * 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 = []; + // Failover value - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); + if (errors.length) { + const failover = internals.default('failover', undefined, errors, helpers); + if (failover !== undefined) { + state.mainstay.tracer.value(state, 'failover', value, failover); + value = failover; + errors = []; } - 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]; + // Error override - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + if (errors.length && + schema._flags.error) { - 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 (typeof schema._flags.error === 'function') { + errors = schema._flags.error(errors); + if (!Array.isArray(errors)) { + errors = [errors]; } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @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; + for (const error of errors) { + Assert(error instanceof Error || error instanceof Errors.Report, 'error() must return an Error object'); + } + } + else { + errors = [schema._flags.error]; + } } - /** - * 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); - } + // Default - /** - * 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 (value === undefined) { + const defaulted = internals.default('default', value, errors, helpers); + state.mainstay.tracer.value(state, 'default', value, defaulted); + value = defaulted; } - /** - * 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; - } + // Cast - /** - * 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; - } + if (schema._flags.cast && + value !== undefined) { - /** - * 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); + const caster = schema._definition.cast[schema._flags.cast]; + if (caster.from(value)) { + const casted = caster.to(value, helpers); + state.mainstay.tracer.value(state, 'cast', value, casted, schema._flags.cast); + value = casted; + } } - /** - * 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); - - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; + // Externals - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; + if (schema.$_terms.externals && + prefs.externals && + prefs._externals !== false) { // Disabled for matching - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; + for (const { method } of schema.$_terms.externals) { + state.mainstay.externals.push({ method, schema, state, label: Errors.label(schema._flags, state, prefs) }); } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + } - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; + // Result - 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); + const result = { value, errors: errors.length ? errors : null }; + + if (schema._flags.result) { + result.value = schema._flags.result === 'strip' ? undefined : /* raw */ helpers.original; + state.mainstay.tracer.value(state, schema._flags.result, value, result.value); + state.shadow(value, schema._flags.result); } - /** - * 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; + // Cache + + if (schema._cache && + prefs.cache !== false && + !schema._refs.length) { + + schema._cache.set(helpers.original, result); } - /** - * 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; + // Artifacts - 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 (value !== undefined && + !result.errors && + schema._flags.artifact !== undefined) { - 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; - } + state.mainstay.artifacts = state.mainstay.artifacts || new Map(); + if (!state.mainstay.artifacts.has(schema._flags.artifact)) { + state.mainstay.artifacts.set(schema._flags.artifact, []); } - } - return true; - } - /** - * 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)); + state.mainstay.artifacts.get(schema._flags.artifact).push(state.path); } - /** - * 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; - } + return result; +}; - /** - * 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; + +internals.prefs = function (schema, prefs) { + + const isDefaultOptions = prefs === Common.defaults; + if (isDefaultOptions && + schema._preferences[Common.symbols.prefs]) { + + return schema._preferences[Common.symbols.prefs]; } - /** - * 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)]; + prefs = Common.preferences(prefs, schema._preferences); + if (isDefaultOptions) { + schema._preferences[Common.symbols.prefs] = prefs; } - /** - * 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 prefs; +}; + + +internals.default = function (flag, value, errors, helpers) { + + const { schema, state, prefs } = helpers; + const source = schema._flags[flag]; + if (prefs.noDefaults || + source === undefined) { + return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); } - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @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; + state.mainstay.tracer.log(schema, state, 'rule', flag, 'full'); + + if (!source) { + return source; } - /** - * 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 = []; + if (typeof source === 'function') { + const args = source.length ? [Clone(state.ancestors[0]), helpers] : []; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); + try { + return source(...args); + } + catch (err) { + errors.push(schema.$_createError(`any.${flag}`, null, { error: err }, state, prefs)); + return; } - } - return result; } - /** - * 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; + if (typeof source !== 'object') { + return source; } - /** - * 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) : []; + if (source[Common.symbols.literal]) { + return source.literal; + } - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; + if (Common.isResolvable(source)) { + return source.resolve(value, state, prefs); } - /** - * 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); - }; + return Clone(source); +}; + + +internals.trim = function (value, schema) { + + if (typeof value !== 'string') { + return value; } - /** - * 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); - }; + const trim = schema.$_getRule('trim'); + if (!trim || + !trim.args.enabled) { + + return value; } - /** - * 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); + return value.trim(); +}; + + +internals.ignore = { + active: false, + debug: Ignore, + entry: Ignore, + filter: Ignore, + log: Ignore, + resolve: Ignore, + value: Ignore +}; + + +internals.errorsArray = function () { + + const errors = []; + errors[Common.symbols.errors] = true; + return errors; +}; + + +/***/ }), + +/***/ 71944: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Assert = __nccwpck_require__(32718); +const DeepEqual = __nccwpck_require__(55801); + +const Common = __nccwpck_require__(72448); + + +const internals = {}; + + +module.exports = internals.Values = class { + + constructor(values, refs) { + + this._values = new Set(values); + this._refs = new Set(refs); + this._lowercase = internals.lowercases(values); + + this._override = false; + } + + get length() { + + return this._values.size + this._refs.size; + } + + add(value, refs) { + + // Reference + + if (Common.isResolvable(value)) { + if (!this._refs.has(value)) { + this._refs.add(value); + + if (refs) { // Skipped in a merge + refs.register(value); + } + } + + return; } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); + // Value + + if (!this.has(value, null, null, false)) { + this._values.add(value); + + if (typeof value === 'string') { + this._lowercase.set(value.toLowerCase(), value); + } } - }, keysIn); } - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @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); + static merge(target, source, remove) { - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; + target = target || new internals.Values(); - var isCommon = newValue === undefined; + if (source) { + if (source._override) { + return source.clone(); + } - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); + for (const item of [...source._values, ...source._refs]) { + target.add(item); + } + } - 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 = []; - } + if (remove) { + for (const item of [...remove._values, ...remove._refs]) { + target.remove(item); + } } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } + + return target.length ? target : null; + } + + remove(value) { + + // Reference + + if (Common.isResolvable(value)) { + this._refs.delete(value); + return; } - else { - isCommon = false; + + // Value + + this._values.delete(value); + + if (typeof value === 'string') { + this._lowercase.delete(value.toLowerCase()); } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); } - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @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; + has(value, state, prefs, insensitive) { + + return !!this.get(value, state, prefs, insensitive); } - /** - * 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); + get(value, state, prefs, insensitive) { + + if (!this.length) { + return false; + } + + // Simple match + + if (this._values.has(value)) { + return { value }; + } + + // Case insensitive string match + + if (typeof value === 'string' && + value && + insensitive) { + + const found = this._lowercase.get(value.toLowerCase()); + if (found) { + return { value: found }; } - } - return iteratee; - }); - } else { - iteratees = [identity]; - } + } - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + if (!this._refs.size && + typeof value !== 'object') { - 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 false; + } + + // Objects + + if (typeof value === 'object') { + for (const item of this._values) { + if (DeepEqual(item, value)) { + return { value: item }; + } + } + } + + // References - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } + if (state) { + for (const ref of this._refs) { + const resolved = ref.resolve(value, state, prefs, null, { in: true }); + if (resolved === undefined) { + continue; + } - /** - * 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); - }); - } + const items = !ref.in || typeof resolved !== 'object' + ? [resolved] + : Array.isArray(resolved) ? resolved : Object.keys(resolved); - /** - * 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 = {}; + for (const item of items) { + if (typeof item !== typeof value) { + continue; + } - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); + if (insensitive && + value && + typeof value === 'string') { - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); + if (item.toLowerCase() === value.toLowerCase()) { + return { value: item, ref }; + } + } + else { + if (DeepEqual(item, value)) { + return { value: item, ref }; + } + } + } + } } - } - return result; + + return false; } - /** - * 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); - }; + override() { + + this._override = true; } - /** - * 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; + values(options) { - 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; + if (options && + options.display) { - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } + const values = []; - /** - * 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; + for (const item of [...this._values, ...this._refs]) { + if (item !== undefined) { + values.push(item); + } + } - 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 values; } - } - return array; + + return Array.from([...this._values, ...this._refs]); } - /** - * 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)); + clone() { + + const set = new internals.Values(this._values, this._refs); + set._override = this._override; + return set; } - /** - * 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); + concat(source) { - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; + Assert(!source._override, 'Cannot concat override set of values'); + + const set = new internals.Values([...this._values, ...source._values], [...this._refs, ...source._refs]); + set._override = this._override; + return set; } - /** - * 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; + describe() { + + const normalized = []; + + if (this._override) { + normalized.push({ override: true }); } - n = nativeFloor(n / 2); - if (n) { - string += string; + + for (const value of this._values.values()) { + normalized.push(value && typeof value === 'object' ? { value } : value); } - } while (n); - return result; - } + for (const value of this._refs.values()) { + normalized.push(value.describe()); + } - /** - * 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 + ''); + return normalized; } +}; - /** - * The base implementation of `_.sample`. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } - /** - * The base implementation of `_.sampleSize` without param guards. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } +internals.Values.prototype[Common.symbols.values] = true; - /** - * 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; +// Aliases - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; +internals.Values.prototype.slice = internals.Values.prototype.clone; - 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]) ? [] : {}); - } +// Helpers + +internals.lowercases = function (from) { + + const map = new Map(); + + if (from) { + for (const value of from) { + if (typeof value === 'string') { + map.set(value.toLowerCase(), value); + } } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; } - /** - * 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; - }; + return map; +}; - /** - * 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 `_.shuffle`. - * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } +/***/ }), + +/***/ 90250: +/***/ (function(module, exports, __nccwpck_require__) { + +/* 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() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.21'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function', + INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); - /** - * 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; + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; - 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; + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; - /** - * 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 to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } + /** + * 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]/; - /** - * 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 match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; - /** - * 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; - } + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - value = iteratee(value); - var valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; - 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); + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; - 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); - } + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; - /** - * 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 = []; + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; - /** - * 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; - } + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - /** - * 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; - } + /** 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; - /** - * 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; + /** 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'; - 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; + /** 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('|') + ')'; - 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; - } + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); - /** - * 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))]; - } + /** + * 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'); - /** - * 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); - } + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - /** - * 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; + /** 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'); - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} + /** 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 + ']'); - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } + /** 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 ]/; - /** - * 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); - } + /** 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' + ]; - /** - * 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); + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; - while (++index < length) { - var array = arrays[index], - othIndex = -1; + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; - /** - * 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 = {}; + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; - /** - * 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 : []; - } + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - /** - * 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; - } + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - /** - * 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)); - } + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); - /** - * 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; + /** Detect free variable `exports`. */ + var freeExports = true && exports && !exports.nodeType && exports; - /** - * 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); - } + /** Detect free variable `module`. */ + var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && 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); - }; + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; - /** - * 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); + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; - buffer.copy(result); - return result; - } + /** 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; - /** - * 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; - } + if (types) { + return types; + } - /** - * 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); - } + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); - /** - * 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; - } + /* 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; - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } + /*--------------------------------------------------------------------------*/ - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + /** + * 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); + } - /** - * 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); + /** + * 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 ((!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; + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); } + return accumulator; + } - /** - * 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; + /** + * 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) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; } - // 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; } + return array; + } - /** - * 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; + /** + * 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 (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; } - return result; } + return array; + } - /** - * 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; + /** + * 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 (++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++]; - } + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; } - return result; } + return true; + } - /** - * 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; + /** + * 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 = []; - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; } - return array; } + return 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) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; + /** + * 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; + } - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + /** + * 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; - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } + while (++index < length) { + if (comparator(value, array[index])) { + return true; } - return object; } + return false; + } - /** - * 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); - } + /** + * 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); - /** - * 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); + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; + } - /** - * 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() : {}; + /** + * 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; - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; + while (++index < length) { + array[offset + index] = values[index]; } + return array; + } - /** - * 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; + /** + * 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; - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } - 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; - }); + /** + * 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; + } - /** - * 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); + /** + * 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; - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } } + return false; + } - /** - * 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; + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } + /** + * 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(''); + } - /** - * 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); + /** + * 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) || []; + } - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); + /** + * 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; } - return wrapper; - } + }); + return result; + } - /** - * 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); + /** + * 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 strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); + /** + * 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); + } - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); + /** + * 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; - return chr[methodName]() + trailing; - }; + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } } + return -1; + } - /** - * 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, ''); - }; - } + /** + * 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 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); + /** + * 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; + } - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } + /** + * 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]; + }; + } - /** - * 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); + /** + * 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; + } - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); + /** + * 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; - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } - 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); + /** + * 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 current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); } - return wrapper; } + return result; + } - /** - * 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; - }; + /** + * 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; + } - /** - * 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; + /** + * 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 (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]; + /** + * 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; + } - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; + /** + * 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); + }; + } - 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]; + /** + * 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 (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; + /** + * 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); + } - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } + /** + * 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; - /** - * 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); + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; + /** + * 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--) { - 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; + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } - 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); + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; } - return wrapper; } + return result; + } - /** - * 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), {}); - }; - } + /** + * 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 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; - }; - } + /** + * 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 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); - }); - }); - }); - } + /** + * 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]; + } - /** - * 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); + /** + * 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]; + } - 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); + /** + * 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); + } + + /** + * 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); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); } + return result; + } - /** - * 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); + /** + * 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); - 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; + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); + /** + * 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; } - return wrapper; } + return result; + } - /** - * 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); - }; - } + /** + * 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); - /** - * 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); - }; - } + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } - /** - * 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; + /** + * 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); - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } - 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 - ]; + /** + * 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; - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); + while (++index < length) { + if (array[index] === value) { + return index; } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); } + return -1; + } - /** - * 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)); - - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; + /** + * 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 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); - }; + /** + * 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); + } - /** - * 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)); - }; - } + /** + * 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); + } - /** - * 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; + /** + * 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 (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; + } - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); + /** + * 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); - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; + /** + * 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; + } - 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); + /** + * 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 (!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); - } + /** + * 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) || []; + } - /** - * 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; - } + /*--------------------------------------------------------------------------*/ - /** - * 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; - } + /** + * 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 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; - } + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; - /** - * 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; + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; - 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; + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; - stack.set(array, other); - stack.set(other, array); + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; + /** Used to generate unique IDs. */ + var idCounter = 0; - 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; - } + /** 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) : ''; + }()); /** - * 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`. + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ - 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; + var nativeObjectToString = objectProto.toString; - 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 to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); - case errorTag: - return object.name == other.name && object.message == other.message; + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; - 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 detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); - case mapTag: - var convert = mapToArray; + /** 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; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); - 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; + /** 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; - // 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; + /* 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; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } + /* 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'); - /** - * 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 to store function metadata. */ + var metaMap = WeakMap && new WeakMap; - 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 lookup unminified function names. */ + var realNames = {}; - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); - 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 to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } + /*------------------------------------------------------------------------*/ /** - * A specialized version of `baseRest` which flattens the rest array. + * 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`. * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Gets metadata for `func`. + * 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. * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. + * 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 */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; + 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); + } /** - * Gets the name of `func`. + * The base implementation of `_.create` without support for assigning + * properties to the created object. * * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; } - } - return result; - } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); /** - * Gets the argument placeholder value for `func`. + * The function whose prototype chain sequence wrappers inherit from. * * @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; + function baseLodash() { + // No operation performed. } /** - * 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. + * The base constructor for creating `lodash` wrapper objects. * * @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. + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; } /** - * Gets the data for `map`. + * 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. * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. + * @static + * @memberOf _ + * @type {Object} */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } + lodash.templateSettings = { - /** - * 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 detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, - while (length--) { - var key = result[length], - value = object[key]; + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, - result[length] = [key, value, isStrictComparable(value)]; + /** + * 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 } - return result; - } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ /** - * Gets the native function at `key` of `object`. + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @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`. + * @constructor + * @param {*} value The value to wrap. */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; } /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * Creates a clone of the lazy wrapper object. * * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } + 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 an array of the own enumerable symbols of `object`. + * Reverses the direction of lazy iteration. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; + return result; + } /** - * Creates an array of the own and inherited enumerable symbols of `object`. + * Extracts the unwrapped value from its lazy wrapper. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); } - return result; - }; + var result = []; - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; + outer: + while (length-- && resIndex < takeCount) { + index += dir; - // 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) : ''; + var iterIndex = -1, + value = array[index]; - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; + 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; + } } } - return result; - }; + result[resIndex++] = value; + } + return result; } + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. + * Creates a hash object. * * @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. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function getView(start, end, transforms) { + function Hash(entries) { var index = -1, - length = transforms.length; + length = entries == null ? 0 : entries.length; + this.clear(); 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; - } + var entry = entries[index]; + this.set(entry[0], entry[1]); } - return { 'start': start, 'end': end }; } /** - * Extracts wrapper details from the `source` body comment. + * Removes all key-value entries from the hash. * * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. + * @name clear + * @memberOf Hash */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; } /** - * Checks if `path` exists on `object`. + * Removes `key` and its value from the hash. * * @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`. + * @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 hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; } /** - * Initializes an array clone. + * Gets the hash value for `key`. * * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - 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; + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; } - return result; + return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** - * Initializes an object clone. + * Checks if a hash value for `key` exists. * * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. + * @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 initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** - * 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`. + * Sets the hash `key` to `value`. * * @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. + * @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 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); + 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; + } - case setTag: - return new Ctor; + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; - case symbolTag: - return cloneSymbol(object); - } - } + /*------------------------------------------------------------------------*/ /** - * Inserts wrapper `details` in a comment at the top of the `source` body. + * Creates an list cache object. * * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - 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'); - } + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - /** - * 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]); + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } /** - * Checks if `value` is a valid array-like index. + * Removes all key-value entries from the list cache. * * @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`. + * @name clear + * @memberOf ListCache */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); + function listCacheClear() { + this.__data__ = []; + this.size = 0; } /** - * Checks if the given arguments are from an iteratee call. + * Removes `key` and its value from the list cache. * * @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`. + * @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 isIterateeCall(value, index, object) { - if (!isObject(object)) { + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { 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); + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); } - return false; + --this.size; + return true; } /** - * Checks if `value` is a property name and not a property path. + * Gets the list cache value for `key`. * * @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`. + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry 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)); + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; } /** - * Checks if `value` is suitable for use as unique object key. + * Checks if a list cache value for `key` exists. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + * @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 isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } /** - * Checks if `func` has a lazy counterpart. + * Sets the list cache `key` to `value`. * * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. + * @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 isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; } - var data = getData(other); - return !!data && func === data[0]; + 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; + + /*------------------------------------------------------------------------*/ + /** - * Checks if `func` has its source masked. + * Creates a map cache object to store key-value pairs. * * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); + 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]); + } } /** - * Checks if `func` is capable of being masked. + * Removes all key-value entries from the map. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + * @name clear + * @memberOf MapCache */ - var isMaskable = coreJsData ? isFunction : stubFalse; + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } /** - * Checks if `value` is likely a prototype object. + * Removes `key` and its value from the map. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + * @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 isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; } /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * Gets the map value for `key`. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function isStrictComparable(value) { - return value === value && !isObject(value); + function mapCacheGet(key) { + return getMapData(this, key).get(key); } /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. + * Checks if a map value for `key` exists. * * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. + * @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 matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; + function mapCacheHas(key) { + return getMapData(this, key).has(key); } /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * Sets the map `key` to `value`. * * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. + * @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 memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; - var cache = result.cache; - return result; + 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; + + /*------------------------------------------------------------------------*/ + /** - * 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. + * Creates an array cache object to store unique values. * * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. + * @constructor + * @param {Array} [values] The values to cache. */ - 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)); + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.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]; + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; } /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. + * Adds `value` to the array cache. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; } /** - * Converts `value` to a string using `Object.prototype.toString`. + * Checks if `value` is in the array cache. * * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. */ - function objectToString(value) { - return nativeObjectToString.call(value); + function setCacheHas(value) { + return this.__data__.has(value); } + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + /** - * A specialized version of `baseRest` which transforms the rest array. + * Creates a stack cache object to store key-value pairs. * * @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. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - 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); - }; + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; } /** - * Gets the parent value at `path` of `object`. + * Removes all key-value entries from the stack. * * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. + * @name clear + * @memberOf Stack */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; } /** - * 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. + * Removes `key` and its value from the stack. * * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. + * @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 reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; + this.size = data.size; + return result; } /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * Gets the stack value for `key`. * * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; + function stackGet(key) { + return this.__data__.get(key); } /** - * 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. + * Checks if a stack value for `key` exists. * * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. + * @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`. */ - var setData = shortOut(baseSetData); + function stackHas(key) { + return this.__data__.has(key); + } /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * Sets the stack `key` to `value`. * * @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. + * @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. */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; + 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; + + /*------------------------------------------------------------------------*/ /** - * Sets the `toString` method of `func` to return `string`. + * Creates an array of the enumerable property names of the array-like `value`. * * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. */ - var setToString = shortOut(baseSetToString); + 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; + + 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; + } /** - * 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. + * A specialized version of `_.sample` for arrays. * * @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`. + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; } /** - * 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. + * A specialized version of `_.sampleSize` for arrays. * * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. + * @returns {Array} Returns the new shuffled array. */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; - - array[rand] = array[index]; - array[index] = value; - } - array.length = size; - return array; + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); } /** - * Converts `string` to a property path array. + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. * * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - 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. + * 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 {*} value The value to inspect. - * @returns {string|symbol} Returns the key. + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; + 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); } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * Converts `func` to its source code. + * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. + * @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 toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } } - return ''; + return -1; } /** - * Updates wrapper `details` based on `bitmask` flags. + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. * * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. + * @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 updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); }); - return details.sort(); + return accumulator; } /** - * Creates a clone of `wrapper`. + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. * * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - 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; + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); } - /*------------------------------------------------------------------------*/ - /** - * 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 + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] + * @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); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] + * @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 chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); + object[key] = value; } - return result; } /** - * 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 + * The base implementation of `_.at` without support for individual paths. * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. */ - function compact(array) { + function baseAt(object, paths) { var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + length = paths.length, + result = Array(length), + skip = object == null; while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } + result[index] = skip ? undefined : get(object, paths[index]); } 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]] + * The base implementation of `_.clamp` which doesn't coerce arguments. * - * console.log(array); - * // => [1] + * @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 concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; + 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 arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + return number; } /** - * 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 + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. * - * _.difference([2, 1], [2, 3]); - * // => [1] + * @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. */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); + 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; - /** - * 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; + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @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; + if (result !== undefined) { + return result; } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); - - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + if (!isObject(value)) { + return value; } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); - } + 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; - /** - * 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 []; + 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; } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); - } + stack.set(value, result); - /** - * 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) - : []; + 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; } /** - * 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 base implementation of `_.conforms` which doesn't clone `source`. * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; } /** - * 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] + * The base implementation of `_.conformsTo` which accepts `props` to check. * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] + * @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 fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = 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 baseFill(array, value, start, end); + return true; } /** - * 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 base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 + * @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 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); + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); } - return baseFindIndex(array, getIteratee(predicate, 3), index); + return setTimeout(function() { func.apply(undefined, args); }, wait); } /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array + * @private * @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 + * @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 findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + if (!length) { - return -1; + return result; } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); + 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; } /** - * 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 + * The base implementation of `_.forEach` without support for iteratee shorthands. * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } + var baseEach = createBaseEach(baseForOwn); /** - * 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 + * The base implementation of `_.forEachRight` without support for iteratee shorthands. * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } + var baseEachRight = createBaseEach(baseForOwnRight, true); /** - * 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] + * The base implementation of `_.every` without support for iteratee shorthands. * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] + * @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 flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + 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 + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } + * @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 fromPairs(pairs) { + function baseExtremum(array, iteratee, comparator) { var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; + length = array.length; while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; + 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; } /** - * 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 + * The base implementation of `_.fill` without an iteratee call guard. * - * _.head([]); - * // => undefined + * @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 head(array) { - return (array && array.length) ? array[0] : undefined; - } + function baseFill(array, value, start, end) { + var length = array.length; - /** - * 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; + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; } - return baseIndexOf(array, value, index); + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; } /** - * Gets all but the last element of `array`. + * The base implementation of `_.filter` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. * - * _.initial([1, 2, 3]); - * // => [1, 2] + * @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 initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; } /** - * 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 + * 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`. * - * _.intersection([2, 1], [2, 3]); - * // => [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`. */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); + var baseFor = createBaseFor(); /** - * 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] + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] + * @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 intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); + var baseForRight = createBaseFor(true); /** - * 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 }]; + * The base implementation of `_.forOwn` without support for iteratee shorthands. * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } /** - * 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 + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); } /** - * 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 + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. * - * _.last([1, 2, 3]); - * // => 3 + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); } /** - * 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 + * The base implementation of `_.get` without support for default values. * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 + * @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 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); + 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 value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); + return (index && index == length) ? object : undefined; } /** - * 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' + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. * - * _.nth(array, -2); - * // => 'c'; + * @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 nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** - * 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']; + * The base implementation of `getTag` without fallbacks for buggy environments. * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - var pull = baseRest(pullAll); + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } /** - * 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']; + * The base implementation of `_.gt` which doesn't coerce arguments. * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] + * @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 pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; + function baseGt(value, other) { + return value > other; } /** - * 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 }]; + * The base implementation of `_.has` without support for deep paths. * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] + * @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 pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); } /** - * 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 }]; + * The base implementation of `_.hasIn` without support for deep paths. * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + * @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 pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; + function baseHasIn(object, key) { + return object != null && key in Object(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'] + * The base implementation of `_.inRange` which doesn't coerce arguments. * - * console.log(pulled); - * // => ['b', 'd'] + * @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`. */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } /** - * 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] + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. * - * console.log(evens); - * // => [2, 4] + * @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 remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; } + array = arrays[0]; + var index = -1, - indexes = [], - length = array.length; + seen = caches[0]; - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { + 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); - indexes.push(index); } } - basePullAt(array, indexes); return result; } /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **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] + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. * - * console.log(array); - * // => [3, 2, 1] + * @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 reverse(array) { - return array == null ? array : nativeReverse.call(array); + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; } /** - * 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. + * The base implementation of `_.invoke` without support for individual + * method arguments. * - * @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`. + * @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 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); + 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); } /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @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 + * The base implementation of `_.isArguments`. * - * _.sortedIndex([30, 50], 40); - * // => 1 + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; } /** - * 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). - * - * @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 - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @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 base implementation of `_.isDate` without Node.js optimizations. * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ - 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; + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; } /** - * 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. - * - * @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 base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 + * @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 sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); + 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); } /** - * 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). - * - * @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 - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 + * @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 sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); - } + 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); - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @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 - * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; } + objIsArr = true; + objIsObj = false; } - return -1; - } + 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__'); - /** - * 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 - * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; - /** - * 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 - * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; + 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); } /** - * 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 implementation of `_.isMap` without Node.js optimizations. * - * _.tail([1, 2, 3]); - * // => [2, 3] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; } /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @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] + * The base implementation of `_.isMatch` without support for iteratee shorthands. * - * _.take([1, 2, 3], 0); - * // => [] + * @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 take(array, n, guard) { - if (!(array && array.length)) { - return []; + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; } /** - * 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] + * The base implementation of `_.isNative` without bad shim checks. * - * _.takeRight([1, 2, 3], 0); - * // => [] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); } /** - * 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'] + * The base implementation of `_.isRegExp` without Node.js optimizations. * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** - * 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'] + * The base implementation of `_.isSet` without Node.js optimizations. * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; } /** - * 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 + * The base implementation of `_.isTypedArray` without Node.js optimizations. * - * _.union([2], [1, 2]); - * // => [2, 1] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } /** - * 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 base implementation of `_.iteratee`. * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; + 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; } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } /** - * 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 }]; + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); + 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; + } /** - * 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 + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * - * _.uniq([2, 1, 2]); - * // => [2, 1] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; + 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; } /** - * 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] + * The base implementation of `_.lt` which doesn't coerce arguments. * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @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 uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + function baseLt(value, other) { + return value < other; } /** - * 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 }]; + * The base implementation of `_.map` without support for iteratee shorthands. * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + * @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 uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; } /** - * 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. + * The base implementation of `_.matches` which doesn't clone `source`. * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] + * @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 unzip(array) { - if (!(array && array.length)) { - return []; + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); } /** - * 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]] + * 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. * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] + * @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 unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; + 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; } - var result = unzip(array); - if (iteratee == null) { - return result; + 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; + } } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); + 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 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 + * The base implementation of `_.nth` which doesn't coerce arguments. * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] + * @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`. */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } /** - * 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. + * The base implementation of `_.orderBy` without param guards. * - * @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 + * @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; + }); + } else { + iteratees = [identity]; + } + + 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); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } /** - * 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] + * The base implementation of `_.pickBy` without support for iteratee shorthands. * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] + * @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. */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; + 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 baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); + return result; + } /** - * 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 }]; + * A specialized version of `baseProperty` which supports deep paths. * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } /** - * 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 + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * @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`. */ - var zip = baseRest(unzip); + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } /** - * 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 + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); + 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 `_.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 + * The base implementation of `_.random` without support for returning + * floating-point numbers. * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 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 + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] + * @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. */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; - - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); + 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; + } /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; + * The base implementation of `_.repeat` which doesn't coerce arguments. * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' + * @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 chain(value) { - var result = lodash(value); - result.__chain__ = true; + 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; } /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example + * The base implementation of `_.rest` which doesn't validate or coerce arguments. * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] + * @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 tap(value, interceptor) { - interceptor(value); - return value; + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); } /** - * 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 + * The base implementation of `_.sample`. * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. */ - function thru(value, interceptor) { - return interceptor(value); + function baseSample(collection) { + return arraySample(values(collection)); } /** - * 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 - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * The base implementation of `_.sampleSize` without param guards. * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] + * @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 wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); + /** + * 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; } - 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); + 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; } - return array; - }); - }); + + 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; + } /** - * 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 } + * The base implementation of `setData` without support for hot loop shorting. * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - function wrapperChain() { - return chain(this); - } + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; /** - * 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] + * The base implementation of `setToString` without support for hot loop shorting. * - * wrapped.last(); - * // => 3 + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. * - * console.log(array); - * // => [1, 2, 3] + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); + function baseShuffle(collection) { + return shuffleSelf(values(collection)); } /** - * 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 } + * The base implementation of `_.slice` without an iteratee call guard. * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } + * @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 wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; - return { 'done': done, 'value': value }; + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + 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 - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true + * The base implementation of `_.some` without support for iteratee shorthands. * - * Array.from(wrapped); - * // => [1, 2] + * @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 wrapperToIterator() { - return this; + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; } /** - * 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] + * 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. * - * wrapped.value(); - * // => [1, 4] + * @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 wrapperPlant(value) { - var result, - parent = this; + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; + 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; + } } - var previous = clone; - parent = parent.__wrapped__; + return high; } - previous.__wrapped__ = value; - return result; + return baseSortedIndexBy(array, value, identity, retHighest); } /** - * 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] + * 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). * - * console.log(array); - * // => [3, 2, 1] + * @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 wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); + 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; } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); } - return this.thru(reverse); + return nativeMin(high, MAX_ARRAY_INDEX); } /** - * 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 + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] + * @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 wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } + 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; - /** - * 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 - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } - * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } } - }); + return result; + } /** - * 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 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + function baseToNumber(value) { + if (typeof value == 'number') { + return value; } - return func(collection, getIteratee(predicate, 3)); + if (isSymbol(value)) { + return NAN; + } + return +value; } /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @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'] + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); + 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; } /** - * 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 `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); - - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @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 `_.uniqBy` without support for iteratee shorthands. * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 + * @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. */ - var findLast = createFind(findLastIndex); + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; - /** - * 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]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); + 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 `_.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 `_.unset`. * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] + * @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 flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; } /** - * 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 `_.update`. * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] + * @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 flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** - * 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 methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * @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 forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); + 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)); } /** - * 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 `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. * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); + 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); } /** - * 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 methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } + * @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. */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; } - }); + var index = -1, + result = Array(length); - /** - * 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; + while (++index < length) { + var array = arrays[index], + othIndex = -1; - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] + * @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. */ - var invokeMap = baseRest(function(collection, path, args) { + function baseZipObject(props, values, assignFunc) { var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; + length = props.length, + valsLength = values.length, + result = {}; - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } return result; - }); + } /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category 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 - * - * 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 } } + * Casts `value` to an empty array if it's not an array like object. * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * 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' } - * ]; + * Casts `value` to `identity` if it's not a function. * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); + function castFunction(value) { + return typeof value == 'function' ? value : identity; } /** - * 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 } - * ]; + * Casts `value` to a path array if it's not one. * - * // 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 {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. */ - 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 castPath(value, object) { + if (isArray(value)) { + return value; } - return baseOrderBy(collection, iteratees, orders); + return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** - * 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 `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + /** + * 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); } /** - * 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 + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * - * var array = [[0, 1], [2, 3], [4, 5]]; + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + buffer.copy(result); + 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'] + * Creates a clone of `arrayBuffer`. * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; } /** - * Gets a random element from `collection`. + * Creates a clone of `dataView`. * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. * - * _.sample([1, 2, 3, 4]); - * // => 2 + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; } /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. + * Creates a clone of the `symbol` object. * - * @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 + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] + * @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. * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); + 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; + } } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); + return 0; } /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] + * @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 shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); + 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; } /** - * 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 + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. * - * _.size('pebbles'); - * // => 7 + * @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 size(collection) { - if (collection == null) { - return 0; + 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]; } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; } - return baseKeys(collection).length; + return result; } /** - * 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 + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true + * @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 some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + 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]; } - return func(collection, getIteratee(predicate, 3)); + 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; } /** - * 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 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * Copies the values of `source` to `array`. * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; + return array; + } + + /** + * 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 = {}); + + 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 baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); + return object; + } - /*------------------------------------------------------------------------*/ + /** + * 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); + } /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). + * Copies own and inherited symbols of `source` to `object`. * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. + * @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 now = ctxNow || function() { - return root.Date.now(); - }; + 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); + }; + } /** - * 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!'); - * }); + * Creates a function like `_.assign`. * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. */ - 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 createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; } - }; + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); } /** - * Creates a 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 + * Creates a `baseEach` or `baseEachRight` function. * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] + * @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 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 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 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 + * Creates a base function for methods like `_.forIn` and `_.forOwn`. * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. */ - 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; + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } } - return result; + return object; }; } /** - * 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!' + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' + * @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. */ - 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; + 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 createWrap(func, bitmask, thisArg, partials, holders); - }); + return wrapper; + } /** - * 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!' + * Creates a function like `_.lowerFirst`. * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. */ - 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 createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + 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; + }; + } /** - * 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] + * Creates a function like `_.camelCase`. * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. */ - 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 createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; } /** - * 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] - * - * curried(1, 2, 3); - * // => [1, 2, 3] + * 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`. * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. */ - 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 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 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 - * })); + * Creates a function that wraps `func` to enable currying. * - * // 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); + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; - if (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; - } + 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]; - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } + 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]; - 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 (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } + /** + * 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); - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; - // 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)); - } + 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; - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); + 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; + } - function trailingEdge(time) { - timerId = undefined; + /** + * 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), {}); + }; + } - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); + /** + * 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); } - lastArgs = lastThis = undefined; return result; - } + }; + } - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } + /** + * 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); + }); + }); + }); + } - function flush() { - return timerId === undefined ? result : trailingEdge(now()); + /** + * 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); + + 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); + } - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); + /** + * 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); - lastArgs = arguments; - lastThis = this; - lastCallTime = time; + 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; - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; } - return result; + return apply(fn, isBind ? thisArg : this, args); } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; + return wrapper; } /** - * 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 + * Creates a `_.range` or `_.rangeRight` function. * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); + 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); + }; + } /** - * 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 + * Creates a function that performs a relational operation on two values. * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } /** - * Creates a function that 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); - * }); + * Creates a function that wraps `func` to continue currying. * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] + * @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 flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); } /** - * Creates a function 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] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] + * Creates a function like `_.round`. * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); + 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)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; + return func(number); }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; } - // Expose `MapCache`. - memoize.Cache = MapCache; - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 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; - * } + * Creates a set object of `values`. * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; /** - * 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 + * Creates a `_.toPairs` or `_.toPairsIn` function. * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. */ - function once(func) { - return before(2, func); + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; } /** - * Creates a function that 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] + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. * - * func(10, 5); - * // => [100, 10] + * @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. */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + 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; - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } /** - * 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' + * 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`. * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * @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. */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } /** - * 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' + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' + * @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. */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); + 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; + } /** - * 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]); + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] + * @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`. */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } /** - * 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 `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' + * @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 rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + 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; } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); + // 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 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' + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 + * @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 spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); + 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 + ''); - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); + 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; } /** - * 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); + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); + * @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 throttle(func, wait, options) { - var leading = true, - trailing = true; + 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 (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + if (objLength != othLength && !isPartial) { + return false; } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); - } + // 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); - /** - * 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 - * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ - function unary(func) { - return ary(func, 1); + 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; } /** - * 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. + * A specialized version of `baseRest` which flattens the rest array. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. + * @private + * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); } - /*------------------------------------------------------------------------*/ - /** - * 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(); - * // => [] + * Creates an array of own enumerable property names and symbols of `object`. * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); } /** - * 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 }]; + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** - * 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); + * Gets metadata for `func`. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; /** - * 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 }]; + * Gets the name of `func`. * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; } /** - * 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); + * Gets the argument placeholder value for `func`. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; } /** - * 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 + * 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. * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false + * @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 conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : 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 + * Gets the data for `map`. * - * _.eq(NaN, NaN); - * // => true + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. */ - function eq(value, other) { - return value === other || (value !== value && other !== other); + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } /** - * 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 + * Gets the property names, values, and compare flags of `object`. * - * _.gt(1, 3); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. */ - var gt = createRelationalOperation(baseGt); + function getMatchData(object) { + var result = keys(object), + length = result.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 + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. * - * _.gte(1, 3); - * // => false + * @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`. */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } /** - * 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 + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * - * _.isArguments([1, 2, 3]); - * // => false + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } /** - * 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 + * Creates an array of the own enumerable symbols of `object`. * - * _.isArray(_.noop); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. */ - var isArray = Array.isArray; + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; /** - * 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 + * Creates an array of the own and inherited enumerable symbols of `object`. * - * _.isArrayBuffer(new Array(2)); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + 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 + * Gets the `toStringTag` of `value`. * - * _.isArrayLike(_.noop); - * // => false + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; } /** - * 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 + * Gets the view, applying any `transforms` to the `start` and `end` positions. * - * _.isArrayLikeObject(_.noop); - * // => false + * @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 isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); + 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 }; } /** - * 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 + * Extracts wrapper details from the `source` body comment. * - * _.isBoolean(null); - * // => false + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; } /** - * 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 + * Checks if `path` exists on `object`. * - * _.isBuffer(new Uint8Array(2)); - * // => false + * @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 isBuffer = nativeIsBuffer || stubFalse; + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } /** - * 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 + * Initializes an array clone. * - * _.isDate('Mon April 23 2012'); - * // => false + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + 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; + } /** - * 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 + * Initializes an object clone. * - * _.isElement(''); - * // => false + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; } /** - * 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 + * Initializes an object clone based on its `toStringTag`. * - * _.isEmpty([1, 2, 3]); - * // => false + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * - * _.isEmpty({ 'a': 1 }); - * // => false + * @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 isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } + 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); } - return true; } /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true + * Inserts wrapper `details` in a comment at the top of the `source` body. * - * object === other; - * // => false + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. */ - function isEqual(value, other) { - return baseIsEqual(value, other); + 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'); } /** - * 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']; + * Checks if `value` is a flattenable `arguments` object or array. * - * _.isEqualWith(array, other, customizer); - * // => true - */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + * @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 an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. + * Checks if `value` is a valid array-like index. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true + * @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; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. * - * _.isError(Error); - * // => false + * @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 isError(value) { - if (!isObjectLike(value)) { + function isIterateeCall(value, index, object) { + if (!isObject(object)) { return false; } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(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 false; } /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * Checks if `value` is a property name and not a property path. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @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 - * - * _.isFinite('3'); - * // => false + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(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)); } /** - * Checks if `value` is classified as a `Function` object. + * Checks if `value` is suitable for use as unique object key. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. * - * _.isFunction(/abc/); - * // => false + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. */ - function isFunction(value) { - if (!isObject(value)) { + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; } /** - * 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 + * Checks if `func` has its source masked. * - * _.isInteger('3'); - * // => false + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); } /** - * 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). + * Checks if `func` is capable of being masked. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang + * @private * @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 + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } + var isMaskable = coreJsData ? isFunction : stubFalse; /** - * 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('')`) + * Checks if `value` is likely a prototype object. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @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 + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; } /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang + * @private * @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 + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; + function isStrictComparable(value) { + return value === value && !isObject(value); } /** - * 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 + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. * - * _.isMap(new WeakMap); - * // => false + * @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 isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } /** - * 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 specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. * - * _.isMatch(object, { 'b': 1 }); - * // => false + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); + 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; } /** - * 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; - * } - * } + * Merges the function metadata of `source` into `data`. * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; + * 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. * - * _.isMatchWith(object, source, customizer); - * // => true + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; } /** - * 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 + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. * - * _.isNaN(NaN); - * // => true + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. * - * _.isNaN(new Number(NaN)); - * // => true + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. * - * isNaN(undefined); - * // => true + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. * - * _.isNaN(undefined); - * // => false + * @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 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; + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** - * 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 + * 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. * - * _.isNative(_); - * // => false + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); + 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 baseIsNative(value); + return array; } /** - * 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 + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * - * _.isNull(void 0); - * // => false + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. */ - function isNull(value) { - return value === null; + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; } /** - * 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 + * Sets metadata for `func`. * - * _.isNil(void 0); - * // => true + * **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. * - * _.isNil(NaN); - * // => false + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - function isNil(value) { - return value == null; - } + var setData = shortOut(baseSetData); /** - * 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 + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * - * _.isNumber(Number.MIN_VALUE); - * // => true + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. * - * _.isNumber(Infinity); - * // => true + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. * - * _.isNumber('3'); - * // => false + * @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 isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** - * 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 + * 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. * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * - * _.isPlainObject(Object.create(null)); - * // => true + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; + 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; } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; + array.length = size; + return array; } /** - * 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 + * Converts `string` to a property path array. * - * _.isRegExp('/abc/'); - * // => false + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + 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; + }); /** - * 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 + * Converts `value` to a string key if it's not a string or symbol. * - * _.isSafeInteger('3'); - * // => false + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * 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 - * - * _.isSet(new Set); - * // => true + * Converts `func` to its source code. * - * _.isSet(new WeakSet); - * // => false + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } /** - * 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 + * Updates wrapper `details` based on `bitmask` flags. * - * _.isString(1); - * // => false + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + 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(); } /** - * 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 + * Creates a clone of `wrapper`. * - * _.isSymbol('abc'); - * // => false + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); + 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; } + /*------------------------------------------------------------------------*/ + /** - * Checks if `value` is classified as a typed array. + * 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 Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @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 * - * _.isTypedArray(new Uint8Array); - * // => true + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] * - * _.isTypedArray([]); - * // => false + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } /** - * Checks if `value` is `undefined`. + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] */ - function isUndefined(value) { - return value === undefined; + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; } /** - * Checks if `value` is classified as a `WeakMap` object. + * Creates a new array concatenating `array` with any additional arrays + * and/or values. * * @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`. + * @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 * - * _.isWeakMap(new WeakMap); - * // => true + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); * - * _.isWeakMap(new Map); - * // => false + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** - * Checks if `value` is classified as a `WeakSet` object. + * 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 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @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 * - * _.isWeakSet(new WeakSet); - * // => true - * - * _.isWeakSet(new Set); - * // => false + * _.difference([2, 1], [2, 3]); + * // => [1] */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); /** - * Checks if `value` is less than `other`. + * 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.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt + * @since 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 * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] * - * _.lt(3, 1); - * // => false + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - var lt = createRelationalOperation(baseLt); + 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)) + : []; + }); /** - * Checks if `value` is less than or equal to `other`. + * 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 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte + * @since 4.0.0 + * @category 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 * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * - * _.lte(3, 1); - * // => false + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; + 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 `value` to an array. + * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. + * @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 * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] + * _.drop([1, 2, 3]); + * // => [2, 3] * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] + * _.drop([1, 2, 3], 2); + * // => [3] * - * _.toArray(1); + * _.drop([1, 2, 3], 5); * // => [] * - * _.toArray(null); - * // => [] + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] */ - function toArray(value) { - if (!value) { + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { return []; } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * Converts `value` to a finite number. + * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. + * @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 * - * _.toFinite(3.2); - * // => 3.2 + * _.dropRight([1, 2, 3]); + * // => [1, 2] * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 + * _.dropRight([1, 2, 3], 2); + * // => [1] * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 + * _.dropRight([1, 2, 3], 5); + * // => [] * - * _.toFinite('3.2'); - * // => 3.2 + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] */ - 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 dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; } - return value === value ? value : 0; + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); } /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * 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 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @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 * - * _.toInteger(3.2); - * // => 3 + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * _.toInteger(Number.MIN_VALUE); - * // => 0 + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] * - * _.toInteger('3.2'); - * // => 3 + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; } /** - * 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). + * 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 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @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 * - * _.toLength(3.2); - * // => 3 + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * _.toLength(Number.MIN_VALUE); - * // => 0 + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] * - * _.toLength(Infinity); - * // => 4294967295 + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] * - * _.toLength('3.2'); - * // => 3 + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; } /** - * Converts `value` to a number. + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. + * @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 * - * _.toNumber(3.2); - * // => 3.2 + * var array = [1, 2, 3]; * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] * - * _.toNumber(Infinity); - * // => Infinity + * _.fill(Array(3), 2); + * // => [2, 2, 2] * - * _.toNumber('3.2'); - * // => 3.2 + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] */ - 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; + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; } - if (typeof value != 'string') { - return value === 0 ? value : +value; + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; } - 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 baseFill(array, value, start, end); } /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. + * 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 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. + * @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 * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 * - * _.toSafeInteger(3.2); - * // => 3 + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 * - * _.toSafeInteger(Number.MIN_VALUE); + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); * // => 0 * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); + 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); } /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @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 * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @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 + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * function Foo() { - * this.a = 1; - * } + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 * - * function Bar() { - * this.c = 3; - * } + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } + 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); + } /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. + * Flattens `array` a single level deep. * * @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 + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } /** - * 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`. + * Recursively flatten `array` up to `depth` times. * * @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 + * @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 * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } + * var array = [1, [2, [3, [4]], 5]]; * - * var defaults = _.partialRight(_.assignInWith, customizer); + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } /** - * 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`. + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. * * @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 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. * @example * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } /** - * Creates an array of values corresponding to `paths` of `object`. + * Gets the first element of `array`. * * @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. + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * _.head([1, 2, 3]); + * // => 1 * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] + * _.head([]); + * // => undefined */ - var at = flatRest(baseAt); + function head(array) { + return (array && array.length) ? array[0] : undefined; + } /** - * 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. + * 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 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. + * @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 * - * 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 + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 * - * circle instanceof Shape; - * // => true + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); } /** - * 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`. + * Gets all but the last element of `array`. * * @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 + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.initial([1, 2, 3]); + * // => [1, 2] */ - var defaults = baseRest(function(object, sources) { - object = Object(object); - - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } - } - - return object; - }); + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. + * 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 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. * @example * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } + * _.intersection([2, 1], [2, 3]); + * // => [2] */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; }); /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. + * 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 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`. + * @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 * - * 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' + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] * * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. + * 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 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`. + * @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 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' + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' + * @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 * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); } /** - * 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`. + * Gets the last element of `array`. * * @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 + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. * @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). + * _.last([1, 2, 3]); + * // => 3 */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; } /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. * * @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 + * @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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); + 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); } /** - * 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`. + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. * * @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 + * @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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * var array = ['a', 'b', 'c', 'd']; * - * Foo.prototype.c = 3; + * _.nth(array, 1); + * // => 'b' * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * _.nth(array, -2); + * // => 'c'; */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. + * 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 Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); - } + var pull = baseRest(pullAll); /** - * Creates an array of function property names from own enumerable properties - * of `object`. + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn + * @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 * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * _.functions(new Foo); - * // => ['a', 'b'] + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; } /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. + * 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 Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions + * @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 * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; } /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. + * 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 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. + * @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 object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; } /** - * Checks if `path` is a direct property of `object`. + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. * * @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`. + * @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 object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); * - * _.has(object, ['a', 'b']); - * // => true + * console.log(array); + * // => ['a', 'c'] * - * _.has(other, 'a'); - * // => false + * console.log(pulled); + * // => ['b', 'd'] */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); /** - * Checks if `path` is a direct or inherited property of `object`. + * 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 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`. + * @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 object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); * - * _.hasIn(object, ['a', 'b']); - * // => true + * console.log(array); + * // => [1, 3] * - * _.hasIn(object, 'b'); - * // => false + * console.log(evens); + * // => [2, 4] */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; } /** - * 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. + * 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 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * var array = [1, 2, 3]; * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - result[value] = key; - }, constant(identity)); + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } /** - * 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). + * 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 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 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } - * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + * @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`. */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; } - - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; } - }, getIteratee); + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } /** - * Invokes the method at `path` of `object`. + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. * * @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. + * @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 * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; - * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] + * _.sortedIndex([30, 50], 40); + * // => 1 */ - var invoke = baseRest(baseInvoke); + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } /** - * 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. + * 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). * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 * - * _.keys('hi'); - * // => ['0', '1'] + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + 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; } /** - * 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). + * 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. * * @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 + * @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 * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); } /** - * 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). + * 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). * * @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 + * @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 * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 * * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** - * 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`. + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. * * @static * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. + * @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 * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } /** - * This method is like `_.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`. + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. * * @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`. + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. * @example * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; - * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } /** - * 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`. + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. * * @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. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); - } - return result; - }); + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } /** - * 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). + * Gets all but the first element of `array`. * * @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. + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } + * _.tail([1, 2, 3]); + * // => [2, 3] */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; } /** - * Creates an object composed of the picked `object` properties. + * Creates a slice of `array` with `n` elements taken from the beginning. * * @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. + * @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 * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * _.take([1, 2, 3]); + * // => [1] * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). + * Creates a slice of `array` with `n` elements taken from the end. * * @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. + * @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 * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * _.takeRight([1, 2, 3]); + * // => [3] * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] */ - function pickBy(object, predicate) { - if (object == null) { - return {}; + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * 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. + * 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 - * @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. + * @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 object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * _.result(object, 'a[0].b.c1'); - * // => 3 + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] * - * _.result(object, 'a[0].b.c2'); - * // => 4 + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] */ - function result(object, path, defaultValue) { - path = castPath(path, object); - - var index = -1, - length = path.length; - - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; - } - return object; + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; } /** - * 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`. + * 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.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`. + * @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 object = { 'a': [{ 'b': { 'c': 3 } }] }; + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 + * // 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'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; } /** - * 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). + * 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. * - * **Note:** This method mutates `object`. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). * * @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`. + * @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 * - * var object = {}; + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); - } + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); /** - * 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. + * 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 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. + * @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); + }); + + /** + * 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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @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 * - * Foo.prototype.c = 3; + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - var toPairs = createToPairs(keys); + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } /** - * 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. + * 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 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. + * @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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ - var toPairsIn = createToPairs(keysIn); + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } /** - * 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`. + * 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.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. + * @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 * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } + function unzip(array) { + if (!(array && array.length)) { + return []; } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); + 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)); }); - return accumulator; } /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. + * 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 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`. + * @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 object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); } /** - * 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). + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * **Note:** This method mutates `object`. + * **Note:** Unlike `_.pull`, this method returns a new array. * * @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`. + * @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 * - * 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 - * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); /** - * 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`. + * 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 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`. + * @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 * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } + * _.xor([2, 1], [2, 3]); + * // => [1, 3] */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * 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 - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] * - * _.values('hi'); - * // => ['h', 'i'] + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); - } + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * 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 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @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 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } - - /*------------------------------------------------------------------------*/ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. + * 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 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. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. * @example * - * _.clamp(-10, -5, 5); - * // => -5 - * - * _.clamp(10, -5, 5); - * // => 5 + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber(number), lower, upper); - } + var zip = baseRest(unzip); /** - * 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. + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. * * @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 + * @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 * - * _.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 - * - * _.inRange(-3, -2, -6); - * // => true + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); } /** - * 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. + * This method is like `_.zipObject` except that it supports property paths. * * @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. + * @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 * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); } - /*------------------------------------------------------------------------*/ - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * 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.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. + * @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 * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); }); + /*------------------------------------------------------------------------*/ + /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.capitalize('FRED'); - * // => 'Fred' + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; } /** - * 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). + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. + * @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 * - * _.deburr('déjà vu'); - * // => 'deja vu' + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + function tap(value, interceptor) { + interceptor(value); + return value; } /** - * Checks if `string` ends with the given target string. + * 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 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`. + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. * @example * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; + function thru(value, interceptor) { + return interceptor(value); } /** - * 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. + * This method is the wrapper version of `_.at`. * - * @static - * @since 0.1.0 + * @name at * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * - * @static + * @name chain * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; + function wrapperChain() { + return chain(this); } /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * Executes the chain sequence and returns the wrapped result. * - * @static + * @name commit * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' + * var array = [1, 2]; + * var wrapped = _(array).push(3); * - * _.kebabCase('fooBar'); - * // => 'foo-bar' + * console.log(array); + * // => [1, 2] * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } /** - * Converts `string`, as space separated words, to lower case. + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * - * @static + * @name next * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. + * @category Seq + * @returns {Object} Returns the next iterator value. * @example * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' + * var wrapped = _([1, 2]); * - * _.lowerCase('fooBar'); - * // => 'foo bar' + * wrapped.next(); + * // => { 'done': false, 'value': 1 } * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } /** - * Converts the first character of `string` to lower case. + * Enables the wrapper to be iterable. * - * @static + * @name Symbol.iterator * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. + * @category Seq + * @returns {Object} Returns the wrapper object. * @example * - * _.lowerFirst('Fred'); - * // => 'fred' + * var wrapped = _([1, 2]); * - * _.lowerFirst('FRED'); - * // => 'fRED' + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] */ - var lowerFirst = createCaseFirst('toLowerCase'); + function wrapperToIterator() { + return this; + } /** - * 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 a clone of the chain sequence planting `value` as the wrapped value. * - * @static + * @name plant * @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. + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.pad('abc', 8); - * // => ' abc ' + * function square(n) { + * return n * n; + * } * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); * - * _.pad('abc', 3); - * // => 'abc' + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); + function wrapperPlant(value) { + var result, + parent = this; - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); + previous.__wrapped__ = value; + return result; } /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * This method is the wrapper version of `_.reverse`. * - * @static + * **Note:** This method mutates the wrapped array. + * + * @name reverse * @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 Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.padEnd('abc', 6); - * // => 'abc ' + * var array = [1, 2, 3]; * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' + * _(array).reverse().value() + * // => [3, 2, 1] * - * _.padEnd('abc', 3); - * // => 'abc' + * console.log(array); + * // => [3, 2, 1] */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; + 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); } /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * Executes the chain sequence to resolve the unwrapped value. * - * @static + * @name value * @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 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. * @example * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padStart('abc', 3); - * // => 'abc' + * _([1, 2, 3]).value(); + * // => [1, 2, 3] */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); } + /*------------------------------------------------------------------------*/ + /** - * 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. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * 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 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.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 * - * _.parseInt('08'); - * // => 8 + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } + }); /** - * Repeats the given string `n` times. + * 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 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. + * @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 {string} Returns the repeated string. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. * @example * - * _.repeat('*', 3); - * // => '***' + * _.every([true, 1, null, 'yes'], Boolean); + * // => false * - * _.repeat('abc', 2); - * // => 'abcabc' + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; * - * _.repeat('abc', 0); - * // => '' + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; } - return baseRepeat(toString(string), n); + return func(collection, getIteratee(predicate, 3)); } /** - * Replaces matches for `pattern` in `string` with `replacement`. + * 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:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). + * **Note:** Unlike `_.remove`, 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. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject * @example * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' + * 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'] */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); } /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * 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 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. + * @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 * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; * - * _.snakeCase('fooBar'); - * // => 'foo_bar' + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' + * // 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 `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); + var find = createFind(findIndex); /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. * * @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. + * @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 * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 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) { - 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); - } + var findLast = createFind(findLastIndex); /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * 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 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. + * @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 * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' + * function duplicate(n) { + * return [n, n]; + * } * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } /** - * Checks if `string` starts with the given target string. + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. * * @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`. + * @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 * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false + * function duplicate(n) { + * return [[[n, n]]]; + * } * - * _.startsWith('abc', 'b', 1); - * // => true + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] */ - 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 flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); } /** - * 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). + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. * * @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 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 * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': '